Lesson 17 of 52Objects
Inheritance and Composition
Reuse behaviour with subclasses, super() and abstract base classes, and know when composition is the better tool.
Once you write more than a handful of classes, you start seeing the same code twice. Python gives you two ways to share it: inheritance ("a Square is a Shape") and composition ("a Car has an Engine"). Choosing well is one of the things that separates junior code from code a team can live with for years, and it is a favourite design question in interviews.
Subclassing: an "is a" relationship
A subclass is a class built on top of another class, its parent (or base class). It gets every attribute and method of the parent for free, and can add new ones or override existing ones by defining a method with the same name.
Press Run (⌘ Enter) to see what happens.introduce is written once in Animal, yet each pet speaks its own way. When introduce calls self.speak(), Python looks up speak starting from the actual object's class. That is polymorphism: one call site, many behaviours.
rex.introduce(): Python first looks in the instance, then in its class Dog. No introduce there.
What does this print?
class Base:
def hello(self):
return "base " + self.name()
def name(self):
return "B"
class Child(Base):
def name(self):
return "C"
print(Child().hello())super(): extend instead of replace
Overriding replaces the parent's method entirely. Usually you want to extend it: do what the parent does, plus a bit more. super() gives you access to the parent's version.
Press Run (⌘ Enter) to see what happens.The classic bug is forgetting super().__init__(...) in a subclass __init__. The parent's setup never runs and self.name does not exist, so you get an AttributeError far from the real mistake.
__init__ but never calls super().__init__(). What happens to the parent's __init__?Multiple inheritance and the MRO
A class can have more than one parent: class Duck(Flyer, Swimmer). Then the lookup order matters. Python computes a method resolution order (MRO) for every class using an algorithm called C3 linearisation. The rules you need: a child comes before its parents, and parents keep the left-to-right order you wrote. Each class appears once, even in a "diamond".
Lookup starts at the class itself, D.
Press Run (⌘ Enter) to see what happens.Look at the second line of output. Inside B, super() did not go to A. It went to the next class in D's MRO, which is C. super() means "the next class in the MRO of this object", not "my parent". That is what makes cooperative multiple inheritance work.
What does this print?
class X: tag = "x" class Y(X): pass class Z(X): tag = "z" class W(Y, Z): pass print(W.tag)
Abstract base classes: a contract for subclasses
Sometimes a parent class should never be used directly. It only defines what subclasses must implement. The abc module makes that enforceable: mark methods with @abstractmethod, and Python refuses to create an instance of any class that has not implemented them all.
Press Run (⌘ Enter) to see what happens.The error arrives when you create the object, not later when some code path finally calls the missing method. That is the point: mistakes surface early.
Protocols: "if it quacks like a duck"
Python has always used duck typing: if an object has the methods you need, you can use it, whatever its class. typing.Protocol lets you write that expectation down for type checkers without forcing anyone to inherit from anything. This is called structural typing: a class matches by its shape, not its family tree.
Press Run (⌘ Enter) to see what happens.Use an ABC when you own the hierarchy and want shared code plus a runtime check. Use a Protocol when you want to accept anything with the right methods, including classes from libraries you cannot change.
Match each tool to what it gives you.
Composition over inheritance
Inheritance is a tight bond. The child depends on every detail of the parent, and deep trees get fragile: change the base and twelve subclasses break. Composition means building an object out of other objects that it has, and delegating work to them.
Imagine a Report that can be exported as PDF or CSV, and sent by email or Slack. With inheritance you need PdfEmailReport, PdfSlackReport, CsvEmailReport, CsvSlackReport: every combination is a class. With composition you pass the parts in:
Press Run (⌘ Enter) to see what happens.Two formatters and two senders give four combinations with four small classes instead of four subclasses (and it grows by addition, not multiplication). Each part is also easy to test alone, and you can swap a real EmailSender for a fake in tests.
A shape hierarchy
Build a small class hierarchy.
Shapeis an abstract base class (abc.ABC) with an abstract methodarea(). It also has a normal methoddescribe()that returns"<ClassName> with area <area to 2 decimals>".Rectangle(width, height)implementsarea().Square(side)inherits fromRectangleand callssuper().__init__instead of re-implementingarea.Circle(radius)implementsarea()usingmath.pi.
Rectangle(2, 3).describe() # "Rectangle with area 6.00"
Square(2).describe() # "Square with area 4.00"
Circle(1).describe() # "Circle with area 3.14"
Shape() # TypeError: can't instantiate abstract classHint: type(self).__name__ gives the class name of the actual object.
Compose a notifier
Use composition: a Notifier does not send anything itself. It holds a channel object and delegates to it.
ListChannelhas a list attributesent(its own list per instance) and a methodsend(to, text)that appends the tuple(to, text)tosent.Notifier(channel)stores the channel.notify(user, message)callschannel.send(user, f"Hi {user}: {message}")and also counts how many notifications it has sent in an attributecount.
ch = ListChannel()
n = Notifier(ch)
n.notify("Ada", "build passed")
ch.sent # [("Ada", "Hi Ada: build passed")]
n.count # 1Our tests will also pass in their own channel class, so Notifier must only rely on the channel having a send(to, text) method.
- subclass
- A class that inherits attributes and methods from a parent and can override them.
- super()
- Returns a proxy to the next class in the object's MRO, used to extend a parent method.
- MRO
- Method resolution order: the list of classes Python searches for an attribute, from
Cls.__mro__. - abstract base class
- A class using
abc.ABCwith@abstractmethods; it cannot be instantiated until they are implemented. - Protocol
- A structural type: any class with the listed methods matches, without inheriting.
- composition
- Building an object from other objects it holds and delegates to (has-a).