Updated March 31, 2023
Introduction to Abstraction in Python
Abstraction in python is defined as hiding the implementation of logic from the client and using a particular application. And the most important key feature of Object-Oriented Programming. It hides the irrelevant data specified in the project, reducing complexity and giving value to efficiency. Abstraction is made in Python using Abstract classes and their methods in the code.
Abstract class Syntax is declared as
from abc import ABC // declaration class classname(ABC);
Abstract method Syntax is declared as
def abstractmethod name(): pass
How does Abstraction work in Python?
As the primary role of Abstraction is to hide the internal functioning of the code, and the interactions are made with the users through the basic implementation. In other words, the user knows what he is doing, not how the works are done behind. So let’s go deeper into the topic to find its importance.
In Python, Abstraction works by incorporating abstract classes and methods.
Abstract Class: A class specified in the code that has abstract methods is named Abstract Class.
Abstract Method: Here, it doesn’t have any implementation. All the implementations are done inside the sub-classes.
Python makes use of a self-variable in method definitions and in initializing a variable. In python, a class method gives information about the class. To define an instant method, this method should declare self as a parameter.
In the Real-world Scenario, let us take an example, while we shop on Amazon or other online shopping, we buy products/ add to cart and pay for them, But when we click on the available options which perform a lot of functionalities behind and that implementation is not available to the user. Only the needed view is given to the user. This is where exactly an abstraction works through the benefit of Hierarchical classification (A Complex Modules are broken into manageable pieces).
Few things to be noted in Python:
- In python, an abstract class can hold both an abstract method and a normal method.
- The second point is an abstract class is not initiated (no objects are created).
- As python doesn’t define an interface, instead, we can use a Keyword abstract class itself.
- The derived class implementation methods are defined in abstract base classes.
Next, we shall see how to declare an Abstract Class with the module. To do so, here we go:
from abc import ABC // here abc and ABC are case-sensitive. When we swap it creates Syntax errors.
Python has the beauty of owning the Module for the base of Abstract Class named ABC – Abstract BaseClass. let us now create an object of the abstract class
class product(ABC): // Abstract Class // Normal Method def item_list(self, rate): // Method Definition print("amount submitted : ",rate) @abstractmethod def product(self,rate): // Abstract Method // Method Definition Pass
Here we have created a class product with two functions: normal and abstract methods. For the abstract method, the subclasses of the product will have their functionalities. It handles the code by dividing them into smaller units.
Examples of Abstraction in Python
Now we shall see an example that shows Abstraction in Python:
from abc import ABC class geometric(ABC): def volume(self): #abstract method pass class Rect(geometric): length = 4 width = 6 height= 6 def volume(self): return self.length * self.width *self.height class Sphere(geometric): radius = 8 def volume(self): return 1.3 * 3.14 * self.radius * self.radius *self.radius class Cube(geometric): Edge = 5 def volume(self): return self.Edge * self.Edge *self.Edge class triangle_3D: length = 5 width = 4 def volume(self): return 0.5 * self.length * self.width rr = Rect() ss = Sphere() cc = Cube() tt = triangle_3D() print("Volume of a rectangle:", rr.volume()) print("Volume of a circle:", ss.volume()) print("Volume of a square:", cc.volume()) print("Volume of a triangle:", tt.volume())
To illustrate the use of abstract class, we have to create an Object for every method here.
from abc import ABC, abstractmethod class Invoice(ABC): def final_bill(self, pay): print('Purchase of the product- ', pay) @abstractmethod def Invoice(self, pay): pass class paycheque(Invoice): def Invoice(self, pay): print('paycheque of- ', pay) class CardPayment(Invoice): def Invoice(self, pay): print('pay through card of- ', pay) aa = paycheque() aa.Invoice(6500) aa.final_bill(6500) print(isinstance(aa,Invoice)) aa = CardPayment() aa.Invoice(2600) aa.final_bill(2600) print(isinstance(aa,Invoice))
So, in the above code, there is an abstract class Invoice, and abstract method invoice () under def statement also has two child class derived from Invoice and does the functionality. Then, using an Object ‘aa’, the methods are invoked.
from abc import ABC, abstractmethod class Bank(ABC): def branch(self, RD): print("Fees submitted : ",RD) @staticmethod @abstractmethod def Bank(RD): pass class private(Bank): @staticmethod def Bank(RD): print("Total RD Value here: ",RD) class XXX(Bank): @staticmethod def Bank(RD): print("Total RD Value here:",RD) private.Bank(500) XXX.Bank(200)
The above code explains how to combine abstract and static methods. So here, the class private and XXX have a static method Bank inside them. And the output is shown below as:
from abc import ABC, abstractmethod class educlass(ABC): def print(self,a): print("The value is: ", a) @abstractmethod def course(self): print("This is educlass") class learn(educlass): def course(self): print("This is test class") class demo_class(educlass): def course(self): print("This is demo class") t1 = learn() t1.course() t1.print(500) ex = demo_class() ex.course() ex.print(850) print("t1 is instance of educlass? ", isinstance(t1, educlass)) print("ex is instance of educlass? ", isinstance(ex, educlass))
Here the code has an abstract method course() and a method print() visible to the user. The inherited class here is demo class and learn and has their course() method. The objects are created for the respective class and invoke the course() method for both of the classes. The hidden pieces of information inside those are getting worked. The isinstance returns a true or false value in python.
Therefore, in this article, we have seen a detailed discussion on the usage of abstraction, an OOPS concept and applied in real-world applications. Abstract classes are especially beneficial when working on projects with other developers where the modules are done parallel. I hope. You all understand the abstract class in Python with their implementation.
This is a guide to Abstraction in Python. Here we discuss the usage of abstraction; an OOPS concept applied in real-world applications. You may also look at the following articles to learn more –