Sub topic 5
Sharing behavior with concrete methods
This chapter assumes you can write a class hierarchy, use @abstractmethod on a base class, and know that instantiating an incomplete subclass raises TypeError.
Abstract and concrete methods can live together
An abstract base class (ABC) does not have to be only a list of required names. It can also hold concrete methods, which are ordinary methods with a full body. Subclasses inherit them without writing any code.
The usual pattern is that concrete methods call abstract ones. The base class fixes the overall steps, and each subclass fills in the steps that differ. This is the template method pattern.
from abc import ABC, abstractmethod
class Exporter(ABC):
def export(self, rows: list[dict]) -> str:
parts = []
header = self.header()
if header:
parts.append(header)
parts.extend(self.format_row(row) for row in rows)
return "\n".join(parts)
def header(self) -> str:
return ""
@abstractmethod
def format_row(self, row: dict) -> str:
"""Turn one row into one line of output."""
class CsvExporter(Exporter):
def header(self) -> str:
return "name,qty"
def format_row(self, row: dict) -> str:
return f"{row['name']},{row['qty']}"
class BulletExporter(Exporter):
def format_row(self, row: dict) -> str:
return f"- {row['name']} x{row['qty']}"
rows = [{"name": "apple", "qty": 3}, {"name": "pear", "qty": 5}]
print(CsvExporter().export(rows))
print(BulletExporter().export(rows))This prints:
name,qty
apple,3
pear,5
- apple x3
- pear x5The three methods play different roles:
| Method | Kind | Subclass duty |
|---|---|---|
| `export` | Concrete, the template | Inherit it unchanged |
| `header` | Concrete, with a default | Override only if needed |
| `format_row` | Abstract | Must implement |
A concrete method that subclasses may override is called a hook. header is a hook.
How the call flows
When you call export on a CsvExporter, Python finds export on Exporter. Inside it, self.header() and self.format_row(...) look up names on the actual object, so they reach the subclass versions.
Why this is safe
The base class can call self.format_row without checking that it exists. Python refuses to create an object while any abstract method is unimplemented, so every real instance has all the methods the template needs. You get the check once, at instantiation, instead of an AttributeError halfway through export.
Design guidance
- Put in the base class only behavior that is true for every subclass. If one subclass has to override a concrete method to undo it, the behavior probably belongs elsewhere.
- Keep the abstract surface small. Each abstract method is a cost for every implementer.
- Give hooks a harmless default, such as an empty string, so subclasses can ignore them.
- Document in the abstract method's docstring what the template expects, such as the return type and whether
Noneis allowed.
Summary
Concrete methods give an ABC two jobs: enforcing an interface and supplying reusable logic. The template method pattern joins them. The base class owns the algorithm, and subclasses supply the abstract pieces and optionally override hooks.
Exercise
Add a concrete method export_count(self, rows) to Exporter that returns the text from export followed by a final line such as 2 rows. Does CsvExporter need any change for the new method to work?
Show answer
Define def export_count(self, rows): return f"{self.export(rows)}\n{len(rows)} rows" in Exporter. CsvExporter needs no change, because it inherits export_count, and the call to self.export reaches the subclass's header and format_row. For two rows, CsvExporter().export_count(rows) returns "name,qty", "apple,3", "pear,5" and "2 rows" on separate lines.