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.

Lab 15: Inheritance, composition, and special methods

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

In this lab you predict which class’s method runs, write two sensor subclasses, watch a dictionary subclass break its own rule and rebuild it by composition, and give classes operators, ordering, length, and iteration. Each exercise ends with a check cell that prints passed or says what is wrong.

Setup

Run the next cell first. It defines Sensor, the base class from the reading.

1. Which method runs?

Read these classes, but don’t run them yet.

class Alert:
    def level(self):
        return "info"

    def message(self, text):
        return f"[{self.level()}] {text}"


class Warning(Alert):
    def level(self):
        return "warning"


class Storm(Warning):
    def message(self, text):
        return super().message(text.upper())

Exercise L15.1 (LO-15.1, ★, about 10 minutes)

Predict, as strings:

  1. m1: Alert().message("wind")

  2. m2: Warning().message("wind")

  3. m3: Storm().message("wind")

and, as a list of class names, m4: the method resolution order of Storm, from Storm to object.

Warning here is a class of this lab’s own, which hides Python’s built-in Warning for the rest of the notebook; that is harmless here, but in your own code, avoid reusing built-in names.

2. Subclasses

Exercise L15.2 (LO-15.1, ★★, about 20 minutes)

Write two subclasses of Sensor:

  • Barometer, with unit = "hPa", whose check extends Sensor’s: after the number check, it raises ValueError unless the pressure is from 870 to 1085 hPa.

  • RainSensor, with unit = "mm", which takes a second argument, area_cm2, the area of its funnel, and stores it. Its check refuses negative amounts with ValueError, and its describe adds , funnel <area_cm2> cm² to Sensor’s line, so that a sensor named "Roof" with a 200 cm² funnel and two readings describes itself as Roof (mm): 2 recorded, funnel 200 cm².

Use super() for everything Sensor already does: don’t copy its code.

3. Inheritance that breaks a rule, and composition that keeps it

A registry maps each station’s name to its Sensor. Its invariant: every key is the name of the sensor it maps to. This version inherits from dict and checks the one way it expected keys to be added. Run it, and watch three other ways in.

Exercise L15.3 (LO-15.2, ★★, about 25 minutes)

  1. Write Registry by composition: it keeps a dictionary in an attribute, _sensors, and offers only these methods:

    • register(sensor) adds a sensor under its own name, and raises ValueError if a sensor with that name is already registered;

    • get(name) returns the sensor with that name, and raises KeyError with a message that names it if there is none;

    • __len__, the number of sensors;

    • __iter__, which gives the names, in alphabetical order.

  2. Set why to the letter of the best reason for choosing composition here:

    • "A": composition is faster than inheritance.

    • "B": a registry isn’t a dictionary in every way a dictionary can be used: as a subclass, it inherits every way to add a key, and must check each one.

    • "C": Python doesn’t allow subclasses of dict.

4. Operators

Exercise L15.4 (LO-15.3, ★★, about 20 minutes)

Finish Vector: add __add__ and __sub__ for two vectors, __mul__ and __rmul__ for a vector and a number (an int or a float), and __neg__, which -v calls. Each returns a new Vector and leaves its operands unchanged, and the binary ones return NotImplemented for an operand they can’t handle.

5. Ordering

Exercise L15.5 (LO-15.3, ★★, about 15 minutes)

TimeOfDay(hour, minute) is a time on a 24-hour clock. Give it __eq__ and __lt__, so that times sort from midnight on, and decorate the class with @functools.total_ordering, which writes <=, >, and >= from those two.

6. Length and iteration

Exercise L15.6 (LO-15.3, ★★, about 20 minutes)

  1. Hours(first, last, step) is an iterator over the hours from first to last, both included if the steps reach last, going up by step. Hours(6, 18, 3) gives 6, 9, 12, 15, and 18. Give it __iter__ and __next__.

  2. Forecast holds one day’s expected temperatures by hour. Give it __len__, the number of hours it holds, and __iter__, which gives (hour, temp) pairs in order of the hour, and can be looped over any number of times.

7. Duck typing

Exercise L15.7 (LO-15.3, ★, about 10 minutes)

This function knows nothing about the classes in this lab:

def busiest(collections):
    """Return the collection with the most items."""
    return max(collections, key=len)

For each call, predict "works" or "error". The calls use the classes from exercises L15.3 and L15.6, so finish those first.

  • d1: busiest([sensors, [1, 2], "abcd"]), with the Registry from exercise L15.3

  • d2: busiest([forecast, Hours(1, 9)])

  • d3: busiest([Forecast(), {}])

Summary

  • A subclass inherits, overrides, and extends its base class’s methods. self.method() in a base class runs the subclass’s version, which is how Sensor.record enforced each subclass’s check.

  • DictRegistry broke its invariant through update, setdefault, and |=, three methods it inherited and never checked. Registry, by composition, offers only the methods that keep it.

  • Special methods connect a class to Python’s operators, to sorting, to len, and to for. An iterable makes a new iterator for each loop; an iterator is used up after one.

  • busiest worked with any object that has a length, whatever its class: duck typing.