Table of Contents

    Mastering Abstract Base Classes in Python: Concepts and Examples

    • An Abstract Base Class or ABC mandates the derived classes to implement specific methods from the base class.

    • It is not possible to create an object from a defined ABC class.

    • Creating objects of derived classes is possible only when derived classes override existing functionality of all abstract methods defined in an ABC class.

    ABC - Example
    • In Python, an Abstract Base Class can be created using module abc.

    Example 1

    from abc import ABC, abstractmethod
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass
        @abstractmethod
        def perimeter(self):
            pass
    • In Example 1, Abstract base class Shape is defined with two abstract methods area and perimeter.
    • With existing abstract class definition of Shape, if you try creating a Shape object it results in TypeError.
    s1 = Shape()

    Output

    TypeError: Can't instantiate abstract class Shape with abstract methods area, perimeter

    class Circle(Shape):
        def __init__(self, radius):
            self.__radius = radius
        @staticmethod
        def square(x):
            return x**2
        def area(self):
            return 3.14*self.square(self.__radius)
    c1 = Circle(3.9)
    • Creating object c1, with out definingperimeter inside derived class, Circle, resulted in TypeError.

    Output

    TypeError: Can't instantiate abstract class Circle with abstract methods perimeter

    • Corrected class definition of Circle, that contains perimeter definition too.
    class Circle(Shape):
        def __init__(self, radius):
            self.__radius = radius
        @staticmethod
        def square(x):
            return x**2
        def area(self):
            return 3.14*self.square(self.__radius)
        def perimeter(self):
            return 2*3.14*self.__radius
    c1 = Circle(3.9)
    print(c1.area())

    Output

    47.7594