Sub topic 3
Cooperating with Parents: `super()` and the MRO
Assume you know Python functions, classes, inheritance, and basic control flow. This chapter focuses on how related classes cooperate and how to choose among common object-oriented designs.
`super()` and the method resolution order
super() delegates a method call to the next class in Python’s method resolution order (MRO). The MRO is the sequence Python searches when it looks up a method. Use ClassName.__init__ less often because it can skip other parent classes in multiple inheritance.
class Logged:
def save(self):
print("log: saving")
class Record(Logged):
def save(self):
super().save()
print("record saved")
Record().save()
print([cls.__name__ for cls in Record.__mro__])The output is:
log: saving
record saved
['Record', 'Logged', 'object']Each overriding method can do its own work and then call super(), allowing the inheritance chain to cooperate.
Polymorphism and duck typing
Polymorphism means one operation works with objects of different types. Python commonly uses duck typing: code accepts an object because it has the needed behavior, rather than because it belongs to a particular class.
def announce(item):
print(item.describe())
class Book:
def describe(self):
return "a book"
class Song:
def describe(self):
return "a song"
for item in (Book(), Song()):
announce(item)The function does not need a shared parent class. It needs a describe method.
Abstract base classes
An abstract base class defines a required interface. A subclass cannot be instantiated until it implements every method marked with @abstractmethod.
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def export(self, data):
...
class TextExporter(Exporter):
def export(self, data):
return ",".join(data)
print(TextExporter().export(["a", "b"]))Use an abstract base class when a shared contract should be explicit. Use duck typing when a small, informal capability is enough.
Dataclasses
A dataclass generates common methods such as __init__, __repr__, and __eq__ from annotated fields.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
print(Point(2, 3))
print(Point(2, 3) == Point(2, 3))Composition or inheritance
Inheritance models an “is-a” relationship. Composition models a “has-a” relationship and often keeps designs more flexible.
class Logger:
def write(self, message):
print(message)
class Service:
def __init__(self, logger):
self.logger = logger
def run(self):
self.logger.write("running")Prefer composition when a class should use a helper without becoming a specialized version of it.
`__slots__`
__slots__ lists permitted instance attributes and can reduce memory use by avoiding a per-instance __dict__. It also prevents adding undeclared attributes.
class Pixel:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = yUse it when many small, stable objects make memory usage important. It adds restrictions, so do not use it automatically.
Exercise
When is composition usually preferable to inheritance?
Show answer
When one object uses another object’s service but is not truly a specialized form of that object.