When several classes should share the same set of methods, such as every shape having an area() or every payment method having a fee(), you can describe that promise in an abstract base class. Python’s abc module lets you mark methods as abstract, so the base class cannot be created on its own and any subclass that forgets a required method fails immediately instead of crashing later. This lesson also shows Protocol, which checks the same kind of promise without inheritance.
In this lesson you will learn
- Creating an abstract base class with
ABC - Marking methods and properties with
@abstractmethod - What happens when a subclass misses a method
- Sharing common code in the base class (the template pattern)
- Structural typing with
typing.Protocol
You should know inheritance and polymorphism.
Abstract Methods
from abc import ABC, abstractmethod
import math
class Shape(ABC):
"""Every shape must know its area and name; the base class cannot be created."""
@abstractmethod
def area(self) -> float:
...
@property
@abstractmethod
def name(self) -> str:
...
def describe(self): # a normal method shared by all shapes
return f"{self.name} with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r ** 2
@property
def name(self):
return "circle"
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
@property
def name(self):
return "square"
for s in [Circle(1.5), Square(4)]:
print(s.describe())
try:
Shape()
except TypeError as e:
print("TypeError:", e)
class Triangle(Shape): # forgot to implement area and name
pass
try:
Triangle()
except TypeError as e:
print("TypeError:", e)
print(isinstance(Square(2), Shape), issubclass(Circle, Shape))
Output
circle with area 7.07
square with area 16.00
TypeError: Can't instantiate abstract class Shape without an implementation for abstract methods 'area', 'name'
TypeError: Can't instantiate abstract class Triangle without an implementation for abstract methods 'area', 'name'
True True
class Shape(ABC)makesShapean abstract base class.@abstractmethodmarksareaas required: every concrete subclass must provide it.- Stacking
@propertyon top of@abstractmethodrequires subclasses to provide a property, herename. - The base class can still contain normal methods.
describe()is written once and works for every shape, because it relies only onarea()andname. Shape()raisesTypeError: an abstract class cannot be instantiated.Triangleforgot both required members, so Python refused to create it, and the error message names exactly what is missing. The mistake shows up as soon as you create an object, not later when someone callsarea().isinstanceandissubclasswork as usual, so code can check “is this a Shape?”.
Template Methods and Protocols
from abc import ABC, abstractmethod
from typing import Protocol
# An abstract base class can define a template: fixed steps, variable details
class PaymentMethod(ABC):
def pay(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
fee = self.fee(amount)
return f"{self.label()}: {amount} + fee {fee} = {amount + fee} taka"
@abstractmethod
def fee(self, amount) -> int: ...
@abstractmethod
def label(self) -> str: ...
class Card(PaymentMethod):
def fee(self, amount):
return round(amount * 0.02)
def label(self):
return "Card"
class MobileWallet(PaymentMethod):
def fee(self, amount):
return 0 if amount < 1000 else 10
def label(self):
return "Mobile wallet"
for method in [Card(), MobileWallet()]:
print(method.pay(1500))
# A Protocol checks structure ("duck typing") without inheritance
class Printable(Protocol):
def to_text(self) -> str: ...
class Invoice: # does not inherit from Printable
def to_text(self):
return "Invoice #42: 1500 taka"
def print_all(items: list[Printable]):
for item in items:
print(item.to_text())
print_all([Invoice()])
Output
Card: 1500 + fee 30 = 1530 taka
Mobile wallet: 1500 + fee 10 = 1510 taka
Invoice #42: 1500 taka
PaymentMethod.paydefines the fixed steps: validate the amount, ask for the fee, and build the receipt. Subclasses only fill in the details that differ,feeandlabel. This is the template method pattern.- Adding a new payment type means writing one small class, and the shared checks cannot be forgotten.
- A
Protocoldescribes the methods an object must have, without requiring inheritance.Invoicenever mentionsPrintable, yet it fits because it has ato_textmethod. - Protocols are checked by type checkers such as mypy, not at run time. They suit “anything with these methods” situations, while ABCs suit families of related classes.
ABC vs Protocol
| Abstract base class | Protocol | |
|---|---|---|
| Module | abc | typing |
| Subclass must inherit? | Yes | No |
| Checked when | At run time, when an object is created | By a type checker, before running |
| Can share code? | Yes, through normal methods | Not usually |
| Best for | Families of classes you control | Accepting any object with the right methods |
Common Mistakes
- Forgetting to inherit from
ABC. Without it,@abstractmethodhas no effect and the class can be created. - Misspelling a method name in the subclass, such as
are(). The ABC catches this as a missing method, which is one of its main benefits. - Making every class abstract. Use an ABC only when several classes really share an interface.
- Putting
@abstractmethodabove@property. The order must be@propertyfirst, then@abstractmethod.
Practice Exercises
Exercise 1. Add a Rectangle(w, h) class to the first example and print its description.
Show answer
class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
@property
def name(self):
return "rectangle"
print(Rectangle(3, 5).describe()) # rectangle with area 15.00
Exercise 2. Add a Cash payment method with no fee to the second example. What is printed for Cash().pay(500)?
Show answer
class Cash(PaymentMethod):
def fee(self, amount):
return 0
def label(self):
return "Cash"
print(Cash().pay(500)) # Cash: 500 + fee 0 = 500 taka
Frequently Asked Questions
Can an abstract method have code in it?
Yes. A subclass must still override it, but it can call the base version with super().method() to reuse shared logic.
Are there ready-made abstract classes in Python?
Yes. collections.abc defines Iterable, Sequence, Mapping and others. Inheriting from them gives you some methods for free; for example, a Sequence that defines __getitem__ and __len__ gets __contains__ and index automatically.
Summary
- Inherit from
ABCand use@abstractmethodto define required methods. - Abstract classes cannot be instantiated, and incomplete subclasses fail early.
- Base classes can hold shared logic that calls the abstract methods.
Protocolchecks for required methods without inheritance.
