Mastering Abstract Base Classes in Python: Concepts and Examples
☰Fullscreen
Table of Content:
-
An
Abstract Base Class
orABC
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 methodsarea
andperimeter
.
- With existing abstract class definition of
Shape
, if you try creating aShape
object it results inTypeError
.
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 inTypeError
.
Output
TypeError: Can't instantiate abstract class Circle with abstract methods perimeter
- Corrected class definition of
Circle
, that containsperimeter
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