Abstraction in Python

Abstraction is one of the important topics of object-oriented programming (OOP) which is used to handle complexity by hiding unnecessary information and showing only essential information to the user. Abstraction becomes very useful when we want to implement or handle complex logic without knowing the hidden complexity. In this article, we will see a real-world example of abstraction, how to define data abstraction in python.

Real World Example of Abstraction:-

For example, when we go to an ATM we can perform various tasks like withdrawing cash, checking balance, retrieving statements, changing a PIN, and many more so while performing these tasks we don’t know the internal implementation of the tasks. That’s how abstraction is useful when we want to show only the required information to the user while hiding other information.

How to Define Data Abstraction in Python:-

We can define an abstract method using @abstractmethod keyword on the top of a method. We can use abc module of python to achieve data abstraction in python. To define an abstract method in python we can import abstractmethod from the abc module of python. Let’s understand how to define data abstraction in python with help of an example.

# abstraction in python
from abc import ABC,abstractmethod

class Prepbytes(ABC):
    @abstractmethod
    def my_method(self):
        # body will always be empty
        Pass

In the above program, First, we import ABC (Abstract Base Class) and abstractmethod from the module abc. After that, we created a class Prepbytes which extends the class ABC and inside the class, we created a method my_method and we used the keyword @abstractmethod on top of the method to define it as an abstract method.

Data Abstraction in Python:-

Let’s understand how we can use the inbuild python class Abstract Base Class (ABC) to achieve data abstraction in python. We can say a class is an abstract class when a class contains an abstract method. We can use @abstractmethod keyword to define an abstract method in python. Let’s understand what is data abstraction in python with help of an example.

# abstraction in python
from abc import ABC,abstractmethod

# abstract class
class Subject(ABC):
    @abstractmethod
    def subject(self):
        pass

class Maths(Subject):
    # override superclass method
    def subject(self):
        print("Subject is Maths")

class Physics(Subject):
    # override superclass method
    def subject(self):
        print("Subject is Physics")

class Chemistry(Subject):
    # override superclass method
    def subject(self):
        print("Subject is Chemistry")

class English(Subject):
    # override superclass method
    def subject(self):
        print("Subject is English")

maths=Maths()
maths.subject()

physics=Physics()
physics.subject()

chemistry=Chemistry()
chemistry.subject()

english=English()
english.subject()
Output:-
Subject is Maths
Subject is Physics
Subject is Chemistry
Subject is English

In the above python program, we created an abstract class Subject which extends Abstract Base Class (ABC). We also defined an abstract method subject. We also created other classes like Maths, Physics, Chemistry, and English which all extend an abstract class Subject thus all these classes are subclasses and the Subject is the superclass. We provided different implementations for the subject method of all the subclasses.

Abstract Class in Python:-

An abstract class is a class that contains both abstract and concrete (normal) methods. Let’s see an example of how an abstract class looks in python.

import abc
from abc import ABC, abstractmethod

class Prepbytes(ABC):
    # an abstract method
    @abstractmethod
    def abstract_method(self):
        print("The abstract method")
    
    # a normal method
    def normal_method(self):
        print("The normal method")

In the above program, we created an abstract class in that we created an abstract method and a normal method. We can implement the abstract method in the subclass and we can call the normal method directly.

We can not directly create an object of an abstract class because an abstract class may contain an abstract method and implementation of an abstract method is not given. Let’s try to understand this with help of an example.

import abc
from abc import ABC, abstractmethod

class Color(ABC):
    # an abstract method
    @abstractmethod
    def print_color(self):
        pass

class Red(Color):
    def print_color(self):
        print("The Color is red")

class Green(Color):
    def print_color(self):
        print("The Color is green")

class Blue(Color):
    def print_color(self):
        print("The Color is blue")

# trying to create an object of an abstract class
obj=Color()
Output:-
Traceback (most recent call last):
File "", line 15, in 
TypeError: Can't instantiate abstract class Prepbytes with abstract methods abstract_method

In the above program, we created an abstract class Color. We try to create an object of the class Color but as an abstract class may contain an abstract method the program will throw an error.

What are Concrete Methods in Abstract Base Class(ABC)?

If a class contains only concrete methods ( normal methods) we can say it is a concrete class. On the other hand, an abstract class contains both normal and abstract methods. The concrete class is mainly used to provide an implementation of the abstract methods of the abstract superclass. Let’s see an example to understand how to use concrete class.

import abc
from abc import ABC, abstractmethod

class SuperClass(ABC):
    @abstractmethod
    def my_method(self):
        print("The abstract superclass")

class SubClass(SuperClass):
	def my_method(self):
		super().my_method()
		print("The subclass")

obj=SubClass()
obj.my_method()
Output:-
The abstract superclass
The subclass

In the above program, we created an abstract class SuperClass with an abstract method my_method. We also created a concrete class SubClass in that we created a normal method my_method which overrides the superclass method we also called super class method using the super() method in a subclass.

Abstract Properties of an Abstract Class:-

An abstract base class of python also provides the functionality of abstract properties along with abstractmethod. We can use the @abstractproperty decorator of the abc module to achieve abstract properties. Abstract properties are generally used to achieve getters and setters functionality.

import abc
from abc import ABC, abstractmethod

class Color(ABC):
    def __init__(self,color):
        self.color=color
    # an abstract method
    @abc.abstractproperty
    def print_color(self):
        pass

class Red(Color):
    def __init__(self):
        super().__init__("Red")
    
    @property
    def print_color(self):
        return self.color

class Green(Color):
    def __init__(self):
        super().__init__("Green")
    
    @property
    def print_color(self):
        return self.color

class Blue(Color):
    def __init__(self):
        super().__init__("Blue")
    
    @property
    def print_color(self):
        return self.color

obj=Green()
print("The color is "+obj.color)
Output:-
The color is Green

In the above program, we created an abstract class Color and created a method print_color method with a keyword @abstractproperty and we also created a constructor to initialize the color variable. We also created subclasses like Red, Green, and Blue which extend an abstract class Color. We implemented a method print_color in every subclass to assign a color of the variable color. On top of every method of the subclass, we set a keyword @property. When we create an object of the subclass first of all constructor of the subclass is called and it set the initial value of the variable color. In the above example, we created an object (obj) of subclass Green so the first constructor of the Green class is called and it set the initial value of color as “Green”. So when we print variable color (obj.color) it will return “Green”.

Leave a Reply

Your email address will not be published. Required fields are marked *