Abstract base classes: a promise every subclass keeps
🌍 In real life. Every plug sold in a country has to fit the same socket. The socket is a standard, not a plug you can use: it says what every real plug must have. A delivery app does the same with its payment methods: card, wallet or cash, each must say what its fee is, or the app can't work out a total.
The idea in one sentence: a class that inherits from ABC and marks some methods with @abstractmethod is a promise, not a finished class: you can't make an object from it, and a subclass can only make objects once it has written every method on the list.
Its words:
- abstract base class (ABC): a class meant only to be inherited from;
from abc import ABC, abstractmethod - abstract method: a method with no real body yet, marked
@abstractmethod; every concrete subclass must write it - concrete class: a subclass that has written all of them, so you can make objects from it
- template method: a normal method in the base class that calls an abstract one, like
total()callingfee()
Step by step:
class Shape(ABC):with@abstractmethodabovedef area(self): ...Shape()is refused with a TypeError: there is no area to useclass Square(Shape):writes its ownareaSquare(3)works, and Shape's other methods can callself.area(), which finds Square's version
Watch the lookups: Square's area hides Shape's empty placeholder, and describe, written once in Shape, is found there:
Why it works. When a class inherits from ABC, Python keeps a list of its methods still marked abstract. A subclass that writes a method with the same name crosses it off. Each time you try to make an object, Python checks that list: if anything is left, it refuses with a TypeError that names the missing methods. So the mistake shows up the moment an object is made, not much later when some rarely used code finally calls the method.
Compare duck typing from Lesson 22.3: any object with an area() works there, with no promise written down. An ABC writes the promise down and checks it. Use it when several classes must share the same methods, such as payment methods or file formats.
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def fee(self, amount):
...
def total(self, amount): # a normal method that uses the abstract one
return amount + self.fee(amount)
class Card(Payment):
def fee(self, amount):
return amount * 2 // 100 # 2 percent
class Cash(Payment):
def fee(self, amount):
return 0
for p in [Card(), Cash()]:
print(type(p).__name__, p.total(500))
try:
Payment()
except TypeError:
print("Payment is only a promise: no objects from it")Mistakes and edge cases.
- forgetting to inherit from ABC:
@abstractmethodon its own checks nothing, soShape()is made quietly and its emptyarea()gives back None - a subclass that misses one method: it is still abstract, and making one raises a TypeError that names what's missing
- a misspelled name (
aerainstead ofarea): the subclass stays abstract, which is exactly how the typo gets caught - an abstract method can still have code: a subclass can use it with
super().area() - making everything abstract: a base class should also hold the shared, finished methods (like
total), so subclasses write only what differs
Quiz
What does this print?
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): ... class Dog(Animal): def sound(self): return "woof" print(Dog().sound()) try: Animal() except TypeError: print("no plain Animal")Cat forgot to write sound. What does this print?
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): ... class Cat(Animal): def purr(self): return "prr" try: Cat() print("made a cat") except TypeError: print("Cat is still abstract")When does Python complain that an abstract method wasn't written?
- When you try to make an object of that class
- Only when the missing method is called
- Never
This class forgot ABC. What does it print?
from abc import abstractmethod class Shape: @abstractmethod def area(self): ... s = Shape() print(s.area())Circle(2) raises a TypeError. Which line is wrong?
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): ... class Circle(Shape): def __init__(self, r): self.r = r def aera(self): return 3 * self.r ** 2 print(Circle(2).area())
Coding tasks
Make
Shapean abstract base class whoseareais abstract (keepdescribe). Then writeRect(w, h), aShapewhosearea()isw * h.Paymentis written for you:feeis abstract andtotaladds it on. WriteCard(fee: 2 percent,amount * 2 // 100) andCash(fee: 0), bothPayments.