abstract-class-in-python

Introduction

Python doesn’t explicitly support abstract classes. In Python, there is a predefined class called ABC of the abc module. ABC class is a Metaclass that defines the behavior of other classes.

Any class that is extended from the abc module is called an abstract class in Python. Abstract class in Python must have at least one abstract method and a concrete method.

The abstract method should be declared in the parent class and should be redefined in the child class. The concrete method is just a normal method. The abstract method should be redefined in child class. And also you cannot create an object of an abstract class. Here, ABC stands for Abstract Base Class.

 

Python code

Let’s see how abstract class in Python

from abc import ABC, abstractmethod

class Parent(ABC):
    
    @abstractmethod
    def display(self):
        pass
    
    def message(self):
        print("message from parent")
        
class Children(Parent):
    def display(self):
        print("re-definition of display function")
        print("child class")
        
c = Children()
c.display()
c.message()

Output

re-definition of display function
child class
message from parent

Explanation

First of all, we imported the ABC class and the abstractmethod decorator from the abc module. The class Parent is extended with the ABC class and defined an abstract method with the name display.

We also defined a concrete class with a name messageThen a child class is created with the name Children. Under this class, we redefined the display method which is an abstract method in the Parent classAnd then we created an object of child class to call the methods in the Parent class.

Points to remember while working with an abstract class

  • Python Virtual Machine(PVM) cannot create an object of abstract class
    from abc import ABC, abstractmethod
    
    class Parent(ABC):
        
        @abstractmethod
        def display(self):
            pass
        
        def message(self):
            print("message from parent")
            
    p = Parent()

    Output

    TypeError                                 Traceback (most recent call last)
    <ipython-input-5-c87a65f77020> in <module>
         10         print("message from parent")
         11 
    ---> 12 p = Parent()
    
    TypeError: Can't instantiate abstract class Parent with abstract methods display

    While trying to create an object of an abstract class, it throws an error. It is because PVM cannot create an object of an abstract class. To make the abstract class function, a child class should be derived from the abstract class and the abstract method should be redefined in the child class as explained earlier.

  • The abstract method should be redefined in child class
    from abc import ABC, abstractmethod
    
    class Parent(ABC):
        
        @abstractmethod
        def display(self):
            pass
        
        def message(self):
            print("message from parent")
    
    class Children(Parent):
        def show(self):
            print("child class")
    
            
    c = Children()
    c.display()
    c.show()

    Output

    TypeError                                 Traceback (most recent call last)
    <ipython-input-6-fa0a1233d706> in <module>
         15 
         16 
    ---> 17 c = Children()
         18 c.display()
         19 c.show()
    
    TypeError: Can't instantiate abstract class Children with abstract methods display

    Here, we got this error because we didn’t redefine the abstract method in child class. So, the abstract method should be redefined in child class.

  • An abstract class can have at least one abstract method and concrete methods too.
    from abc import ABC, abstractmethod
    
    class Parent(ABC):
        
        @abstractmethod
        def display(self):
            pass
        
        @abstractmethod
        def message(self):
            pass
        
        def show(self):
            print("show method in abstract class")
    
    class Children(Parent):
    
        def display(self):
            print("display method is redefine")
            
        def message(self):
            print("message method is redefine")
            
    c = Children()
    c.display()
    c.message()
    c.show()

    Output

    display method is redefine
    message method is redefine
    show method in abstract class

    This shows that an abstract class can have at least one abstract method and a concrete method too.

 

Use case of abstract class

If you are designing any system that has two classes that have some similar properties/features and some dissimilar properties in it, you can make use of the abstract class.

from abc import ABC, abstractmethod

class School(ABC):
    @abstractmethod
    def task(self):
        pass
    
    def NameOfSchool(self):
        print("School : XYZ")

class Teacher(School):
    def task(self):
        print("Task is to teach the students.")
        
class Student(School):
        def task(self):
            print("Task is to learn from teachers.")
            
teachers = Teacher()
students = Student()

teachers.NameOfSchool()
teachers.task()

print()

students.NameOfSchool()
students.task()

Output

School : XYZ
Task is to teach the students.

School : XYZ
Task is to learn from teachers.

Here common feature that objects of both Teacher and Student share is “name of school” and the feature that is different from each other is “task”. This is a simple example of the implementation of an abstract class.

 

Conclusion

An abstract class should have at least one abstract method and concrete methods too. PVM cannot create an object of an abstract class. To make an abstract class, it should be extended with the ABC class and should use the abstractmethod decorator. One should keep in mind that if you inherit an abstract class that has an abstract method in it, you must either redefine the abstract method in the child class or you should make the child class an abstract class.

If you are new to oop concepts, check this blog. To learn more about abc module check this documentation

Happy learning 🙂

Leave a Reply

Your email address will not be published.