×

Abstraction in Python

What is meant by abstraction generally?

A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but not a detailed overview of the content is known as Abstraction.

What is Abstraction in Python?

The process where the user is exposed only to the outer view but not the detailed structure or functioning of the program is known as Abstraction.

Abstraction can be defined as:

The process of giving access only to certain essential or required details to the user and hiding the unnecessary or unwanted details from the user so that the task that is supposed to be completed is not affected is known as Abstraction.

Abstraction is a process in which the complexity of the problem is hidden, and just the outwork is showcased.

So, let us consider a real-time example that describes abstraction.

Example:

When we play a game on a PC or a mobile phone, we are just aware of the controls, how to play, what makes you score more, what makes you move forward, what makes you move backwards, etc.

We are just allowed to know the game's outer view and the keys or controls required to play the game. We do not know how the game's functioning happens within the program, what program the game consists of, and how the keys are being enabled right after they are addressed.

All these features have been hidden from the user interface so that there will be no duplication and verifying that the main motive of the task is not being disturbed. In the same way, this is the actual process that takes place within a python program while undergoing abstraction.

Let us look forward to the advantages of using abstraction.

Advantages of using Abstraction:

  1. Redundancy or duplication of the programs can be easily avoided.
  2. Provides high security for the program or an application.
  3. No changes can be made in the internal parts of the system program as there will be no allowance or access to the user.
  4. Generates code reusability without any errors.
  5. Code optimization.

Abstraction in python can be implemented in two ways:

  1. By using Abstract class
  2. By using Interface
Abstraction in Python

What is an Abstract Class and an Abstract Method?

Abstract class:

A class defined or declared with at least one Abstract method within its body is known as an Abstract class.

Abstract classes can be used when we want to implement large functions within the body. The subclass inherits the abstract class, and the abstract methods get their definitions in the subclass. This is how the flow of code processing occurs while using abstract classes and abstract methods.

In python, we cannot create an abstract class directly. To use abstract classes, we are supposed to import ABC, i.e., " Abstract Base Class ", from an inbuilt module " abc “.

Abstract Base Classes ( ABC ) :

The classes that act as intermediate classes in order to perform implementations within the other classes are known as " Abstract Base Classes ". It works similarly to the Application Programming Interface ( API ). We use plugins while implementing ABC. We can import Abstract Base Classes from the " abc module ”. We must use ABC to include abstraction in python. A method is said to be an abstract method when declared with the keyword " @abstractmethod ".

The syntax for creating an Abstract class:

from abc import ABC
class ClassName(ABC):
    #statements

Let’s consider an example program:

Example program:

#importing abstract base class from abc module
from abc import ABC, abstractmethod
class Vehicles(ABC):
    @abstractmethod
    def noofwheels(self):
        pass
class Car(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Car: I have 4 wheels")
class Cycle(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Cycle: I have 2 wheels")


class Bike(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Bike: I have 2 wheels")
class Auto(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Auto: I have 3 wheels")
class Truck(Vehicles):
    #overriding the abstract method
    def noofwheels(self):
        print("Truck: I have 6 wheels")
obj1 = Car()
obj1.noofwheels()
obj2 = Cycle()
obj2.noofwheels()
obj3 = Bike()
obj3.noofwheels()
obj4 = Auto()
obj4.noofwheels()
obj5 = Truck()
obj5.noofwheels()

Output:

Car: I have 4 wheels
Cycle: I have 2 wheels
Bike: I have 2 wheels
Auto: I have 3 wheels
Truck: I have 6 wheels

Explanation:

Initially, " abstract base class " is imported from the " abc module “. A class    “ Vehicles ” is declared with an abstract method which is represented by  “ @abstractmethod ", and then a common method " noofwheels() ", is declared, which describes the number of wheels that the specified vehicle generally consists of. Thereafter, every class with different vehicles used the abstract method " noofwheels() “ to print separate statements.

The statements have been printed successfully. We've used abstract classes to optimize the code. The code might have been lengthier if the abstract class is not used here.


Related Topics

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

How to Plot Graphs Using Python?

In this article, we are going to learn about how to plot different types of graphs using Python. We are going to use different approaches for every type of graph....

3 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

Python program to find the GCD or HCF

Python program to find the GCD or HCF The largest positive integer that perfectly divides the two numbers is the HCF (Highest Common Factor) or GCD (Greatest Common Deviser). For example,...

5 minutes read.