Skip to content

Lesson 17 of 52Objects

Inheritance and Composition

Reuse behaviour with subclasses, super() and abstract base classes, and know when composition is the better tool.

16 min read0/5 questions

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.

Python
class Animal: def __init__(self, name): self.name = name def speak(self): return "..." def introduce(self): return f"I am {self.name} and I say {self.speak()}" class Dog(Animal): def speak(self): # override return "woof" class Cat(Animal): def speak(self): return "meow" for pet in [Dog("Rex"), Cat("Tom"), Animal("Blob")]: print(pet.introduce()) print(isinstance(Dog("x"), Animal), issubclass(Cat, Animal))
Output
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.

Where does Python find a method?
objectevery class ends hereDogspeakCatspeakAnimal__init__, speak, introduceroot

rex.introduce(): Python first looks in the instance, then in its class Dog. No introduce there.

1/4
Predict the outputPython

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())
Need a nudge? Hints walk you through it.

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.

Python
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def describe(self): return f"{self.name} earns {self.salary}" class Manager(Employee): def __init__(self, name, salary, reports): super().__init__(name, salary) # let the parent set name and salary self.reports = reports def describe(self): return super().describe() + f" and manages {len(self.reports)}" m = Manager("Priya", 120_000, ["Sam", "Leo"])print(m.describe())
Output
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.

Quick check
A subclass defines __init__ but never calls super().__init__(). What happens to the parent's __init__?
Need a nudge? A hint rules out a wrong answer.

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".

The diamond: class D(B, C), both B and C inherit A
D1BCAobject

currentwaitingdone

Lookup starts at the class itself, D.

1/4
Python
class A: def who(self): return "A"class B(A): def who(self): return "B then " + super().who()class C(A): def who(self): return "C then " + super().who()class D(B, C): pass print([cls.__name__ for cls in D.__mro__])print(D().who())
Output
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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Python
from abc import ABC, abstractmethod class PaymentProvider(ABC): @abstractmethod def charge(self, cents: int) -> str: ... def charge_dollars(self, dollars: float) -> str: # shared helper return self.charge(round(dollars * 100)) class FakeStripe(PaymentProvider): def charge(self, cents): return f"charged {cents} cents" print(FakeStripe().charge_dollars(9.99)) class Broken(PaymentProvider): pass try: Broken()except TypeError as e: print("TypeError:", e)
Output
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.

Python
from typing import Protocol class Closeable(Protocol): def close(self) -> None: ... class File: def close(self) -> None: print("file closed") class Socket: def close(self) -> None: print("socket closed") def shutdown(things: list[Closeable]) -> None: for t in things: t.close() shutdown([File(), Socket()]) # neither inherits from Closeable
Output
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 the pairs0/4 matched

Match each tool to what it gives you.

Choose an item, then its match on the other side.

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:

Python
class CsvFormatter: def format(self, rows): return "\n".join(",".join(map(str, r)) for r in rows) class UpperFormatter: def format(self, rows): return " | ".join(str(r).upper() for r in rows) class PrintSender: def send(self, body): print("sending:\n" + body) class Report: def __init__(self, formatter, sender): self.formatter = formatter # Report HAS a formatter self.sender = sender # and HAS a sender def publish(self, rows): self.sender.send(self.formatter.format(rows)) Report(CsvFormatter(), PrintSender()).publish([["Ada", 3], ["Sam", 5]])Report(UpperFormatter(), PrintSender()).publish(["ok", "done"])
Output
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.

Quick check
Which relationship is the best fit for inheritance?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

A shape hierarchy

Build a small class hierarchy.

  • Shape is an abstract base class (abc.ABC) with an abstract method area(). It also has a normal method describe() that returns "<ClassName> with area <area to 2 decimals>".
  • Rectangle(width, height) implements area().
  • Square(side) inherits from Rectangle and calls super().__init__ instead of re-implementing area.
  • Circle(radius) implements area() using math.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 class

Hint: type(self).__name__ gives the class name of the actual object.

Python
import mathfrom abc import ABC, abstractmethod class Shape(ABC): # Declare an abstract area() and a describe() method. pass class Rectangle(Shape): pass class Square(Rectangle): pass class Circle(Shape): pass
ChallengeEasy

Compose a notifier

Use composition: a Notifier does not send anything itself. It holds a channel object and delegates to it.

  • ListChannel has a list attribute sent (its own list per instance) and a method send(to, text) that appends the tuple (to, text) to sent.
  • Notifier(channel) stores the channel. notify(user, message) calls channel.send(user, f"Hi {user}: {message}") and also counts how many notifications it has sent in an attribute count.
ch = ListChannel()
n = Notifier(ch)
n.notify("Ada", "build passed")
ch.sent      # [("Ada", "Hi Ada: build passed")]
n.count      # 1

Our tests will also pass in their own channel class, so Notifier must only rely on the channel having a send(to, text) method.

Python
class ListChannel: pass class Notifier: def __init__(self, channel) -> None: pass def notify(self, user: str, message: str) -> None: pass
Key terms
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.ABC with @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).