Lesson 14 of 15 · Design
Abstract Base Classes
Learn abstract classes in Python with the abc module: what abstract and concrete classes are, how @abstractmethod forces child classes to follow an interface, and when to use them.
- 7 min read
- Intermediate
- Reviewed
- What abstract and concrete classes are
- How to write an abstract class with ABC and @abstractmethod
- What happens when a child forgets a required method
- How an abstract class can share normal methods too
- When to use an abstract class instead of duck typing
A class that is only a plan
Think of the word "vehicle". You can buy a car, a bus or a scooter, but you cannot buy just "a vehicle". "Vehicle" is a general idea. It says what every vehicle must be able to do, such as start and stop, without being any particular one.
Writing an abstract class
Python's abc module (short for "abstract base classes") provides two tools: the parent class ABC and the decorator @abstractmethod.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return round(3.14159 * self.radius ** 2, 2)
for shape in [Square(4), Circle(2)]:
print(type(shape).__name__, shape.area())Shape inherits from ABC, which makes it abstract. area is marked with @abstractmethod, so it is required. Square and Circle both override area, so they are concrete and work normally.
The rules are checked for you
Two things are now impossible. First, you cannot create the abstract class itself:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
try:
shape = Shape()
except TypeError:
print("Shape is abstract, so it cannot be created directly")Second, a child that forgets a required method cannot be created either:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
# oops: no area() method
try:
triangle = Triangle(6, 3)
except TypeError:
print("Triangle forgot to write area(), so Python refuses to create it")Python raises a TypeError that names the missing method. This is the big advantage: the mistake is caught the moment you try to create the object, not hours later when some code finally calls triangle.area().
Abstract classes can share real code too
An abstract class can also contain normal, finished methods. They are inherited like any others, and they can even call the abstract methods, trusting that every child will provide them.
from abc import ABC, abstractmethod
class Report(ABC):
def __init__(self, title):
self.title = title
@abstractmethod
def body(self):
pass
def render(self): # a normal, shared method
line = "=" * len(self.title)
return f"{self.title}\n{line}\n{self.body()}"
class SalesReport(Report):
def __init__(self, title, total):
super().__init__(title)
self.total = total
def body(self):
return f"Total sales: {self.total}"
class TeamReport(Report):
def __init__(self, title, people):
super().__init__(title)
self.people = people
def body(self):
return "Team: " + ", ".join(self.people)
print(SalesReport("November Sales", 48250).render())
print()
print(TeamReport("AI Team", ["Ada", "Alan", "Grace"]).render())Every report gets the same render() layout for free. Each child only fills in the one part that is different: its body().
Abstract classes or duck typing?
In the Polymorphism lesson, duck typing worked without any shared parent. So when should you use an abstract class?
| Duck typing | Abstract base class |
|---|---|
| No parent needed, very flexible | Children must inherit from the parent |
| A missing method is found only when it is called | A missing method is found as soon as the object is created |
| Good for small scripts and loose connections | Good for frameworks, plugins and team projects |
Use an abstract class when other people will write child classes, for example in a library or a large team, and you want a clear, checked list of what they must provide.
Common mistakes
Write an abstract notifier that sets the rules, plus two concrete notifiers that follow them.
from abc import ABC, abstractmethod
# 1. Write an abstract class Notifier(ABC) with:
# - an abstract method send(self, message)
# - a normal method alert(self, message) that returns self.send("ALERT: " + message)
# 2. Write EmailNotifier, whose send returns "Email -> " + message
# 3. Write SmsNotifier, whose send returns "SMS -> " + message
for notifier in [EmailNotifier(), SmsNotifier()]:
print(notifier.alert("Server is down"))
try:
Notifier()
except TypeError:
print("Notifier is abstract")
# Output must be exactly:
# Email -> ALERT: Server is down
# SMS -> ALERT: Server is down
# Notifier is abstract
An abstract class Shape requires area(). A child class Hexagon does not define area(). What happens when you run Hexagon()?
Summary
- An abstract class is a parent-only class that lists methods every child must provide.
- Make one by inheriting from
ABCand marking required methods with@abstractmethod. - Abstract classes, and children that miss a required method, cannot be created. Python raises a
TypeError. - A concrete class provides every required method and works normally.
- Abstract classes can also share finished methods that call the required ones.
Next: the final project, where you bring everything together.
Finished reading? Tick it off to track your progress.