An abstract base class is a parent class that only describes what its children must have. You cannot create an object from it, and a child class that forgets one of the required methods cannot be created either.
The program
python
from abc import ABC, abstractmethod import math class Shape(ABC): @abstractmethod def area(self): ... @abstractmethod def perimeter(self): ... def describe(self): return f"{type(self).__name__}: area {self.area():.2f}, perimeter {self.perimeter():.2f}" class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 def perimeter(self): return 2 * math.pi * self.radius for shape in [Rectangle(4, 6), Circle(1)]: print(shape.describe())
output
Rectangle: area 24.00, perimeter 20.00 Circle: area 3.14, perimeter 6.28
How it works
class Shape(ABC)makes Shape abstract.@abstractmethodmarksareaandperimeteras methods that every child class must define....(the Ellipsis) is an empty body. It does the same here aspass.describeis a normal method. The children inherit it, and it can callarea()andperimeter()because every child is guaranteed to have them.
A child that forgets a method
Python checks when you create the object, not when you call the missing method:
python
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): ... @abstractmethod def perimeter(self): ... class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 # perimeter is missing try: Shape() except TypeError as e: print("Error:", e) try: Square(3) except TypeError as e: print("Error:", e)
output
Error: Can't instantiate abstract class Shape without an implementation for abstract methods 'area', 'perimeter' Error: Can't instantiate abstract class Square without an implementation for abstract method 'perimeter'
The error shows up as soon as someone writes Square(3), with the name of the missing method. Without the abstract base class, the program would run until something called perimeter(), and only then fail.