Inheritance lets a subclass reuse or replace behavior supplied by its base classes.
Python inheritance: override behavior without inventing shared ownership
Operation contract
The receipt exporter base defines a format contract, and the JSON exporter implements it. The import report receives an exporter instance rather than constructing a particular subclass inside the report method. That keeps selection separate from use and permits a direct test of the chosen behavior.
Failure and ownership boundary
Inheritance is a type relationship, not automatic resource ownership or input validation. Deep hierarchies can make method resolution and initialization harder to inspect. Prefer an injected collaborator when the design is about replacing one operation, and read Python classes: keep instance state separate from class state before assuming a base class makes subclass lists independent.
Working program
class ReceiptExporter:
def render(self, identifier):
raise NotImplementedError("export format required")
class JsonReceiptExporter(ReceiptExporter):
def render(self, identifier):
import json
return json.dumps({"receipt_id": identifier}, sort_keys=True)
def export_receipt(exporter, identifier):
return exporter.render(identifier)
print(export_receipt(JsonReceiptExporter(), 41))Output
{"receipt_id": 41}Costs and limits
The dispatch retains one collaborator reference; serialization grows with the response shape. No network, file ownership or polymorphic performance comparison is claimed.
Common Mistakes
- A type hierarchy is not a cleanup policy.
- Keep implementation selection visible at construction.
Connected lessons
Python classes: keep instance state separate from class state, Python JSON validation: reject duplicate members and non-integer amounts, Java interfaces and replaceable behavior.
Apply this boundary
Python super and method resolution: cooperate across mixins.
Follow the related contract
Python ABC: prevent construction of an incomplete implementation, Python metaclasses: validate a class before registering its wire format.
