Sub topic 8
Requiring overrides with abstract base classes
This chapter assumes you can define classes, use self, write subclasses that override methods, and call super(). It also assumes you have seen polymorphism, where one call works on many related types.
The problem: a forgotten override
A base class often describes a method that only subclasses can fill in. A plain base class cannot enforce this. If a subclass forgets to override the method, the mistake can stay hidden until the call runs.
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
pass # forgot to override area()
c = Circle() # no error here
try:
c.area() # error only appears now
except NotImplementedError:
print("area() was never implemented")The object is created without complaint. The failure shows up later, possibly far from the mistake. An abstract base class (ABC) moves that failure to the moment of instantiation.
Declaring abstract methods
The abc module provides ABC and the abstractmethod decorator. A class that inherits from ABC and has at least one abstract method cannot be instantiated. Each concrete subclass must override every abstract method.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
shapes = [Square(2), Square(3)]
print([s.area() for s in shapes]) # [4, 9]
try:
Shape()
except TypeError as exc:
print("Cannot instantiate:", exc)The last call raises TypeError, because Shape still has an unimplemented abstract method. The Square class is concrete because it overrides area().
What happens with an incomplete subclass
A subclass that does not override every abstract method is itself abstract. Python rejects it when you try to create an instance, not when you define the class.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
class Circle(Shape):
pass # still abstract
try:
Circle()
except TypeError as exc:
print("TypeError:", exc)The error message names the missing method, which makes the mistake easy to find.
Abstract methods can have a body
An abstract method may contain code. Subclasses can reach it through super(). This is useful for shared default behavior that every subclass should still decide to use explicitly.
from abc import ABC, abstractmethod
class Report(ABC):
@abstractmethod
def title(self):
return "Report"
class SalesReport(Report):
def title(self):
return super().title() + ": Sales"
print(SalesReport().title()) # Report: SalesSalesReport must still override title(). The body in Report is only used if the subclass chooses to call it.
Using an ABC for polymorphism
An ABC gives callers a contract. Code that accepts a Shape can rely on area() existing, so it works with any concrete subclass.
def total_area(shapes):
return sum(s.area() for s in shapes)
print(total_area([Square(1), Square(4)])) # 17(This reuses Square from the earlier example.) Adding a new shape never requires changing total_area.
Common errors
- Forgetting
ABC. If the class does not inherit fromABC(or usemetaclass=ABCMeta),@abstractmethodis not enforced and the class can be instantiated. - Misspelling the override. If the subclass defines
aera()instead ofarea(), the abstractarea()remains and instantiation fails. This is the check working as intended. - Expecting an error at class definition. The
TypeErrorappears when you instantiate, not when you write the subclass. - Putting
@abstractmethodoutside other decorators. When combining it with@property, place@abstractmethodas the innermost decorator, directly above thedef.
Exercise
A class Base(ABC) declares two abstract methods, load() and save(). A subclass Child(Base) overrides only load(). What happens when you run Child(), and what happens when you run class Child(Base): ... alone?
Show answer
Child() raises TypeError, because save() is still abstract and Child is therefore still abstract. Defining the class alone raises no error. Python checks for remaining abstract methods only at instantiation.
Exercise
Why might you choose an ABC over a base class whose method raises NotImplementedError?
Show answer
With an ABC, the error appears as soon as someone tries to create an instance of an incomplete class. With NotImplementedError, the error appears only when the missing method is called, which can be much later.