Python Abstract Base Classes
An abstract class is a class that names methods its children must provide. Python refuses to build an object from a class with a missing method.
An abstract class cannot be built
Shape marks area as abstract. Building Shape itself now fails.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
try:
Shape()
except TypeError as error:
print(f"TypeError: {error}")A child must finish the job
This uses the Shape class from above. Square provides area, but Blob does not.
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
print(Square(3).area())
class Blob(Shape):
pass
try:
Blob()
except TypeError as error:
print(f"TypeError: {error}")An abstract property
A child must provide the label property too. Here Tag provides it as a normal property.
from abc import ABC, abstractmethod
class Label(ABC):
@property
@abstractmethod
def label(self):
pass
class Tag(Label):
@property
def label(self):
return "sale"
print(Tag().label)Registering a virtual subclass
Sketch never inherits from Drawable. Registering still makes isinstance answer True.
from abc import ABC
class Drawable(ABC):
pass
class Sketch:
def draw(self):
return "drawing"
Drawable.register(Sketch)
print(isinstance(Sketch(), Drawable))Example
import math
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
def describe(self):
return f"Area: {self.area():.2f}"
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
try:
Shape()
except TypeError as error:
print(f"TypeError: {error}")
circle = Circle(2)
square = Square(3)
print(circle.describe())
print(square.describe())Key points
- Abstract class: a class that names methods its children must provide
- Use abc.ABC as the parent to make a class abstract
- Use @abstractmethod to mark a method that children must write
- Abstract property: a property that children must provide
- Virtual subclass: a class registered as a subclass without inheriting
- Registering a virtual subclass does not check its methods
In this example, Shape is an abstract base class. It marks area as abstract, so Shape itself cannot be built. The try block proves this and prints the TypeError. Shape also has a normal method, describe, which calls self.area(). Circle provides area with the circle formula. Square provides area by squaring its side. Both children can be built because both finished the job. Their describe calls use the shared code with each child's own area.
Note
Python checks abstract methods only when you build an object.
Duck typing and Protocols, taught later, check shape in other ways.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A subclass leaves out one abstract method. What happens when you try to build an object from it?