Composition and inheritance
Composition lets an object use another object to do part of its work. Inheritance lets a specialized type reuse behavior from a base class. Choose the relationship that expresses how callers use the objects.
On this page
Compose a report
A report needs somewhere to write text. Give it an object with a write method. A memory buffer provides that method and makes the result easy to inspect.
from io import StringIO
class Report:
def __init__(self, destination):
self.destination = destination
def add_line(self, text):
self.destination.write(text + "\n")
buffer = StringIO()
report = Report(buffer)
report.add_line("Tests passed")
print(buffer.getvalue().strip())The report controls the line format. The destination controls where text goes. A file opened for writing could be supplied through the same constructor.
Specialize a type
class Notice:
def heading(self):
return "Notice"
class WarningNotice(Notice):
def heading(self):
return "Warning"
for item in [Notice(), WarningNotice()]:
print(item.heading())Both objects support the same method call. Python looks up the method on each instance’s type and uses the override for the warning. The two output lines are Notice and Warning.