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 75There are three ways a subclass uses its base class here:
Inherit:
Thermometerdefines no__init__,record, ordescribe, so it usesSensor’s. When Python looks upair.record, it searches the instance, thenThermometer, thenSensor, and stops at the first class that defines the name. The order it searches is the class’s method resolution order, which__mro__shows; every class ends withobject.Override: each subclass defines its own
checkand its ownunit, which replaceSensor’s.recordis defined only inSensor, but itsself.check(value)calls the subclass’scheck, becauseselfis aThermometer. That is how onerecordmethod enforces every kind of sensor’s rules. The traceback shows it:record, inSensor, calledcheckinThermometer.Extend:
super()gives the base class’s version of a method.super().check(value)runs the number check first, then the subclass adds its own range check.Anemometer.__init__callssuper().__init__(name)to setnameandvalues, then addsheight_m; itsdescribeadds to the base’s line instead of rewriting it.
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.6RainLog 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.0Every 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:
| Question | Inheritance | Composition |
|---|---|---|
| Is the new class a kind of the other, in every way the other can be used? | Yes: a thermometer is a sensor | No: a rain log isn’t a list |
| Must it offer all of the other’s methods? | It gets all of them, wanted or not | It offers only the ones it chooses |
| Can it change which object it uses while running? | No: the base class is fixed | Yes: a station can swap a broken sensor |
| How tightly is it tied to the other class? | Closely: a change in the base changes every subclass | Loosely: 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)morning + eveningcallsmorning.__add__(evening), which returns a new vector and leaves both operands unchanged, as+does for numbers.morning * 2calls__mul__. For0.5 * morning, Python first triesfloat.__mul__, which returnsNotImplementedbecause a float can’t multiply a vector, then tries the reflected method on the right operand,morning.__rmul__(0.5).abs(morning)calls__abs__: the vector’s length, , whichmath.hypotcomputes.total += windworks without an__iadd__method: Python falls back tototal = total + wind.For a type the method doesn’t handle, each returns
NotImplemented, and if the other operand doesn’t handle it either, Python raisesTypeError:morning + 1givesTypeError: unsupported operand type(s) for +: 'Vector' and 'int'.
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.partsfrom 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 TrueTuples 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 dayfrom 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¶
| Misconception | What’s true | An example that breaks it |
|---|---|---|
A subclass’s __init__ runs its base class’s __init__ by itself | Only 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 rules | The subclass inherits every way to change the list | RainLog(list) with a checked append still accepts extend([-5.0]) |
Defining __lt__ gives every comparison | Each operator has its own method | Version("3.9") <= Version("3.12") raises TypeError |
An object that works in one for loop works in every one | An iterator is used up after one pass | The second list(week) is [] |
+ on my objects should change the left operand | + returns a new object, like it does for numbers | After morning + evening, morning is still Vector(3, 4) |
Summary¶
A subclass inherits its base class’s methods, overrides the ones it defines, and extends a method by calling the base’s version with
super(). Python finds a method by searching the class, then its bases, in the method resolution order.Use inheritance when the new class is a kind of the base and can keep every promise the base makes. Otherwise, use composition: hold the other object in an attribute, and offer only the methods that keep the invariant.
Special methods connect your class to Python’s syntax:
__add__,__mul__, and__rmul__to operators,__lt__and the other comparisons to<and sorting,__len__tolen, and__iter__and__next__tofor. ReturnNotImplementedfor types a method can’t handle.Duck typing means code uses whatever an object can do, whatever its class. It makes code general, and moves errors to the moment a missing ability is used.
Self-check¶
A
Sensorsubclass,Hygrometer, measures humidity from 0 to 100 percent. Write it withunit = "%"and acheckthat 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. Callingsuper().check(value)first keeps the number check, so"50"raisesTypeErrorbefore the comparison could fail.A
Gardenhas anameand a set of plants, and must never hold more than 20. Should it inherit fromset, or hold one? Why?Answer
Hold one. A garden isn’t a set in every way a set can be used:
setoffersadd,update,|=, and more, and each would have to be overridden to keep the limit of 20. Composition offers onlyplant(name)and whatever else the garden needs, each with its check.With
Vectoras above, what does2 * Vector(1, 1) + Vector(0, 3)give, and which special methods run, in order?Answer
Vector(2, 5).int.__mul__(2, vector)returnsNotImplemented, so Python callsVector.__rmul__, which calls__mul__and givesVector(2, 2). Then__add__addsVector(0, 3).Why does a
forloop over aRainLogwork twice in a row, while one over aDaysobject works only once?Answer
RainLog.__iter__returns a new iterator over its list each time a loop starts.Days.__iter__returnsself, which keeps its place; after one loop, itsnext_dayis pastlast, so the next loop stops at once.A function
longest(items)returns the item with the largestlen. Which of these can it take, by duck typing: a list of strings, a list ofRainLogobjects, a list ofDaysobjects?Answer
The strings and the rain logs, which both define
__len__.Dayshas no__len__, solen(days)raisesTypeError: object of type 'Days' has no len().
Further reading¶
Allen B. Downey, Think Python, 3rd edition, chapter 17, Inheritance. A larger class hierarchy, playing cards, decks, and hands, with delegation and specialization.
The Python Tutorial, chapter 9, Classes, sections 9.5 (Inheritance) and 9.8 (Iterators). The official account of
super, multiple inheritance, and the iterator protocol.The Python Language Reference, Data model, the section “Special method names”. Every special method Python calls, and when it calls the reflected ones.