Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 15: Inheritance, composition, and special methods

Objectives: LO-15.1, LO-15.2, LO-15.3
Prerequisites: Module 14
Time: about 5.5 hours: 2 for this reading, 2 for Lab 15, and 1.5 for the practice

Module 14’s classes stood alone. This module shows two ways to build a class from another one: inheritance, where a new class is a kind of an existing class and takes on its methods, and composition, where a class holds other objects and uses them. Knowing when to choose each is one of the main skills of designing with classes. The module ends with more special methods, the ones that let your objects work with +, <, len, and for, as Python’s own types do.

Work in a new folder, m15, in your py101 folder, and save each example there.

Inheritance

A weather station has several sensors. Every sensor records numbers and refuses values that can’t be readings, but each kind has its own unit and its own rules. Save this as sensors.py:

"""Sensors that record readings, each with its own rules."""


class Sensor:
    """A sensor that records numeric readings.

    Invariant: every value in values passed check().
    """

    unit = ""

    def __init__(self, name):
        self.name = name
        self.values = []

    def check(self, value):
        """Raise an exception if value can't be a reading from this sensor."""
        if not isinstance(value, (int, float)):
            raise TypeError(f"a reading must be a number, not {value!r}")

    def record(self, value):
        """Check value, then record it."""
        self.check(value)
        self.values.append(value)

    def describe(self):
        """Return one line about the sensor."""
        return f"{self.name} ({self.unit}): {len(self.values)} recorded"


class Thermometer(Sensor):
    """A sensor for air temperature."""

    unit = "°C"

    def check(self, value):
        super().check(value)
        if not -90 <= value <= 60:
            raise ValueError(f"a temperature must be from -90 to 60 °C, not {value}")


class Anemometer(Sensor):
    """A sensor for wind speed, mounted at a height above the ground."""

    unit = "km/h"

    def __init__(self, name, height_m):
        super().__init__(name)
        self.height_m = height_m

    def check(self, value):
        super().check(value)
        if not value >= 0:
            raise ValueError(f"a wind speed can't be negative: {value}")

    def describe(self):
        return super().describe() + f", at {self.height_m} m"

class Thermometer(Sensor): makes Thermometer a subclass of Sensor, its base class. A thermometer has every attribute and method a sensor has, and can change some of them. Save this as sensors_demo.py, and run it:

from sensors import Anemometer, Sensor, Thermometer

air = Thermometer("Harbor air")
wind = Anemometer("Harbor wind", 10)
air.record(8.5)
wind.record(22)
wind.record(31.5)
for sensor in [air, wind]:
    print(sensor.describe())
print(isinstance(wind, Sensor), isinstance(wind, Thermometer))
print(Anemometer.__mro__)
air.record(75)
Harbor air (°C): 1 recorded
Harbor wind (km/h): 2 recorded, at 10 m
True False
(<class 'sensors.Anemometer'>, <class 'sensors.Sensor'>, <class 'object'>)
Traceback (most recent call last):
  File "/home/ada/py101/m15/sensors_demo.py", line 12, in <module>
    air.record(75)
  File "/home/ada/py101/m15/sensors.py", line 23, in record
    self.check(value)
  File "/home/ada/py101/m15/sensors.py", line 39, in check
    raise ValueError(f"a temperature must be from -90 to 60 °C, not {value}")
ValueError: a temperature must be from -90 to 60 °C, not 75

There are three ways a subclass uses its base class here:

isinstance(wind, Sensor) is True: an instance of a subclass is an instance of its base class too, so code written for sensors works with every kind.

Composition, and when to choose it

Inheritance says “a thermometer is a sensor”. Composition says “a station has sensors”: a Station class would keep its sensors in an attribute and call their methods. Both reuse code; the difference is in what the new class promises.

A subclass promises everything its base class promises, because code written for the base class will use it. That is the test for inheritance: can the subclass keep every promise of the base, with all of the base’s methods? Here is a class that fails the test. A rain log must never hold a negative amount, and inheriting from list seems to give it everything a list can do. Save this as loglist.py:

class RainLog(list):
    """Daily rain amounts, in millimeters. Invariant: no amount is negative."""

    def append(self, mm):
        if not mm >= 0:
            raise ValueError(f"rain can't be negative: {mm}")
        super().append(mm)


log = RainLog()
log.append(2.4)
log.extend([-5.0])
log.insert(0, -1.0)
log += [-3.0]
print(log, len(log), sum(log))
[-1.0, 2.4, -5.0, -3.0] 4 -6.6

RainLog checks append, but it inherited every other method of list, and extend, insert, and += add values without calling append. To keep its invariant, it would have to override every one of them, and any method a later Python version adds to list. A rain log isn’t a list with rules: it is something that uses a list.

With composition, the class keeps the list in an attribute and offers only the operations that keep its invariant. Save this as rainlog.py:

class RainLog:
    """Daily rain amounts, in millimeters. Invariant: no amount is negative."""

    def __init__(self):
        self._amounts = []

    def add(self, mm):
        """Record one day's rain."""
        if not mm >= 0:
            raise ValueError(f"rain can't be negative: {mm}")
        self._amounts.append(mm)

    def total(self):
        """Return the total rain."""
        return sum(self._amounts)

    def __len__(self):
        return len(self._amounts)

    def __iter__(self):
        return iter(self._amounts)
from rainlog import RainLog

log = RainLog()
for mm in [2.4, 0.0, 12.0]:
    log.add(mm)
print(len(log), log.total(), list(log), max(log))
3 14.4 [2.4, 0.0, 12.0] 12.0

Every way into the list goes through add, and log.extend([-5.0]) raises AttributeError, because the class never offered it. The delegating methods, __len__ and __iter__, pass the work to the list inside, so len, list, max, and for still work; the next section explains them.

To choose between the two:

QuestionInheritanceComposition
Is the new class a kind of the other, in every way the other can be used?Yes: a thermometer is a sensorNo: a rain log isn’t a list
Must it offer all of the other’s methods?It gets all of them, wanted or notIt offers only the ones it chooses
Can it change which object it uses while running?No: the base class is fixedYes: a station can swap a broken sensor
How tightly is it tied to the other class?Closely: a change in the base changes every subclassLoosely: only the methods it calls matter

When the answer isn’t clearly “is a”, prefer composition. It keeps each class’s promises small and its invariant in one place.

Special methods

Python’s built-in operations call special methods (also called “dunder” methods, for their double underscores) on your objects: len(x) calls x.__len__(), a + b calls a.__add__(b), and so on. Module 14 used __init__, __repr__, and __eq__. Defining the others lets your objects work with the same syntax as numbers, strings, and lists.

Arithmetic operators

Wind is a vector: it has an east part and a north part, and two winds combine by adding the parts. Save this as vector.py:

import math


class Vector:
    """A two-dimensional vector, such as a wind's east and north parts in km/h."""

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Vector({self.x!r}, {self.y!r})"

    def __eq__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

    def __add__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, factor):
        if not isinstance(factor, (int, float)):
            return NotImplemented
        return Vector(self.x * factor, self.y * factor)

    def __rmul__(self, factor):
        return self * factor

    def __abs__(self):
        return math.hypot(self.x, self.y)
from vector import Vector

morning = Vector(3, 4)
evening = Vector(-1, 2)
print(morning + evening, morning * 2, 0.5 * morning, abs(morning))
total = Vector(0, 0)
for wind in [morning, evening, Vector(0, -1)]:
    total += wind
print(total)
Vector(2, 6) Vector(6, 8) Vector(1.5, 2.0) 5.0
Vector(2, 5)

Comparison

Version numbers sort wrongly as text: sorted(["3.9", "3.12", "3.10"]) gives ['3.10', '3.12', '3.9'], because strings compare character by character and "1" comes before "9". A class with __lt__ (less than) compares them as numbers. Save this as version.py:

class Version:
    """A version number such as 3.12, compared part by part."""

    def __init__(self, text):
        self.parts = tuple([int(part) for part in text.split(".")])
        self.text = text

    def __repr__(self):
        return f"Version({self.text!r})"

    def __eq__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts == other.parts

    def __lt__(self, other):
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts < other.parts
from version import Version

names = ["3.9", "3.12", "3.10"]
print(sorted([Version(name) for name in names]), max([Version(name) for name in names]))
print(Version("3.9") < Version("3.12"), Version("3.12") > Version("3.9"))
[Version('3.9'), Version('3.10'), Version('3.12')] Version('3.12')
True True

Tuples compare item by item, so (3, 9) < (3, 12) is True. sorted, min, and max need only <, and a > b works too, because Python tries b.__lt__(a) when a has no __gt__ of its own. But Version("3.9") <= Version("3.12") raises TypeError: '<=' not supported between instances of 'Version' and 'Version': each comparison has its own method (__lt__, __le__, __gt__, and __ge__). The decorator functools.total_ordering writes the missing ones from __eq__ and __lt__, and @dataclass(order=True) writes all four from the fields.

Length and iteration

len(x) calls x.__len__(), which must return an int of 0 or more. A for loop calls iter(x), which calls x.__iter__() to get an iterator, then calls next on the iterator, which calls its __next__, until it raises StopIteration. RainLog.__iter__ above returned the list’s own iterator. A class can be its own iterator too, by defining both methods. Save this as days.py:

from datetime import timedelta


class Days:
    """An iterator over the dates from first to last, both included."""

    def __init__(self, first, last):
        self.next_day = first
        self.last = last

    def __iter__(self):
        return self

    def __next__(self):
        if self.next_day > self.last:
            raise StopIteration
        day = self.next_day
        self.next_day += timedelta(days=1)
        return day
from datetime import date

from days import Days

week = Days(date(2026, 11, 28), date(2026, 12, 1))
for day in week:
    print(day, day.strftime("%A"))
print(list(week))
2026-11-28 Saturday
2026-11-29 Sunday
2026-11-30 Monday
2026-12-01 Tuesday
[]

The loop crosses the end of November because timedelta does the calendar arithmetic. The second line shows the catch: an iterator keeps its place, and once it has raised StopIteration it is exhausted, so list(week) is empty. An iterable, such as a list or RainLog, makes a new iterator each time iter is called, so it can be looped over again and again. Module 16’s generators make iterators like Days in a few lines.

Duck typing

“If it walks like a duck and quacks like a duck, it is a duck.” Python code doesn’t usually check an object’s class; it calls the methods it needs, and any object that has them works. This function adds up anything it can loop over:

def report(amounts):
    count = 0
    total = 0
    for mm in amounts:
        count += 1
        total += mm
    return f"{count} days, {total:.1f} mm"

report([2.4, 0.0, 12.0]), report((5.0, 1.5)), a RainLog, and the values of a dictionary all work, with no shared base class, because each has __iter__ and yields numbers. That is duck typing: what matters is what an object can do, not what class it belongs to. It is why RainLog needed only __iter__ to work with for, list, max, and sum.

Duck typing has a cost: a wrong object fails only when the missing ability is used. report(Days(...)) starts the loop, then raises TypeError: unsupported operand type(s) for +=: 'int' and 'datetime.date' at the first addition. A docstring that says what the argument must do, and the type hints of Module 14, tell readers and type checkers what kind of duck is expected.

Common misconceptions

MisconceptionWhat’s trueAn example that breaks it
A subclass’s __init__ runs its base class’s __init__ by itselfOnly if it calls super().__init__(...)An Anemometer.__init__ that only sets height_m makes record raise AttributeError: 'Anemometer' object has no attribute 'values'
Inheriting from list is a good way to make a list with rulesThe subclass inherits every way to change the listRainLog(list) with a checked append still accepts extend([-5.0])
Defining __lt__ gives every comparisonEach operator has its own methodVersion("3.9") <= Version("3.12") raises TypeError
An object that works in one for loop works in every oneAn iterator is used up after one passThe second list(week) is []
+ on my objects should change the left operand+ returns a new object, like it does for numbersAfter morning + evening, morning is still Vector(3, 4)

Summary

Self-check

  1. A Sensor subclass, Hygrometer, measures humidity from 0 to 100 percent. Write it with unit = "%" and a check that extends the base’s check.

    Answer

    class Hygrometer(Sensor):
        """A sensor for relative humidity."""
    
        unit = "%"
    
        def check(self, value):
            super().check(value)
            if not 0 <= value <= 100:
                raise ValueError(f"humidity must be from 0 to 100 %, not {value}")

    It needs no __init__: Sensor’s is enough. Calling super().check(value) first keeps the number check, so "50" raises TypeError before the comparison could fail.

  2. A Garden has a name and a set of plants, and must never hold more than 20. Should it inherit from set, or hold one? Why?

    Answer

    Hold one. A garden isn’t a set in every way a set can be used: set offers add, update, |=, and more, and each would have to be overridden to keep the limit of 20. Composition offers only plant(name) and whatever else the garden needs, each with its check.

  3. With Vector as above, what does 2 * Vector(1, 1) + Vector(0, 3) give, and which special methods run, in order?

    Answer

    Vector(2, 5). int.__mul__(2, vector) returns NotImplemented, so Python calls Vector.__rmul__, which calls __mul__ and gives Vector(2, 2). Then __add__ adds Vector(0, 3).

  4. Why does a for loop over a RainLog work twice in a row, while one over a Days object works only once?

    Answer

    RainLog.__iter__ returns a new iterator over its list each time a loop starts. Days.__iter__ returns self, which keeps its place; after one loop, its next_day is past last, so the next loop stops at once.

  5. A function longest(items) returns the item with the largest len. Which of these can it take, by duck typing: a list of strings, a list of RainLog objects, a list of Days objects?

    Answer

    The strings and the rain logs, which both define __len__. Days has no __len__, so len(days) raises TypeError: object of type 'Days' has no len().

Further reading