Python: Abstract Class

Abstract class works as a blueprint for other classes. We can not instantiate an abstract class, but extend it.

Abstract class contains abstract methods, which do not definition of the method. We need to add the definition of those abstract methods, in the child(class that extends abstract class) class.

WARNING

Abstract classes and methods are not directly built into the Python programming language.

Abstract feature supported by a module named “abc“. Module name “abc” represents “Abstract Base Class“.

from abc import ABC


class BigBoxAbs(ABC):
    pass
Python
from abc import ABC, abstractmethod


class BigBoxAbs(ABC):

    @abstractmethod
    def my_abs_method(self): 
        ...
Python
from abc import ABC, abstractmethod


class BigBoxAbs(ABC):

    @abstractmethod
    def my_abs_method(self): 
        ...


class MyCls(BigBoxAbs):
    pass


obj = MyCls()
Python

Output:

Traceback (most recent call last):
  File "abs_example.py", line 12, in <module>
    obj = MyCls()
TypeError: Can't instantiate abstract class MyCls with abstract method my_abs_method
Plaintext
from abc import ABC, abstractmethod


class BigBoxAbs(ABC):

    @abstractmethod
    def my_abs_method(self): 
        ...


class MyCls(BigBoxAbs):
    def my_abs_method(self):
        print("My abs method...")


obj = MyCls()
obj.my_abs_method()
Python

Output:

My abs method...
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.