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.

Objectives: LO-14.1, LO-14.2, LO-14.3, LO-14.4
Prerequisites: the Module 14 reading and Lab 12
Time: about 2 hours

In this lab you predict what a class’s instances hold, write a class with methods, write a thermostat that keeps its invariant whatever its callers do, give a class a readable __repr__ and an __eq__, rebuild it as a frozen dataclass, and add type hints. Each exercise ends with a check cell that prints passed or says what is wrong.

Setup

Run the next cell first. It imports what the checks need and seeds random, which the thermostat’s check uses to try many calls in a repeatable order.

1. Instances and methods

Read this class and the lines after it, but don’t run anything yet.

class Tally:
    def __init__(self, label):
        self.label = label
        self.marks = []

    def mark(self, value):
        self.marks.append(value)
        return len(self.marks)


rain = Tally("rain")
wind = Tally("wind")
rain.mark(2.4)
n = rain.mark(0.0)
wind.mark(7)
m = Tally.mark(wind, 3)

Exercise L14.1 (LO-14.1, ★, about 10 minutes)

Predict:

  1. p1: the value of n.

  2. p2: the value of m. Tally.mark(wind, 3) calls the method through the class, passing the instance yourself.

  3. p3: len(rain.marks), after all the lines have run.

  4. p4: rain.marks is wind.marks, True or False.

Now run the class and check your predictions.

2. A class of your own

Exercise L14.2 (LO-14.1, ★★, about 20 minutes)

Write a class Station for a weather station:

  • Station("Harbor") creates a station with the attribute name and no temperatures yet.

  • add(temp) records one temperature, and returns nothing.

  • count() returns how many temperatures it has recorded.

  • mean() returns their mean, and raises ValueError with a message that says there are no temperatures when there are none.

  • extremes() returns a tuple of the lowest and the highest temperature, and raises ValueError the same way when there are none.

3. Keeping an invariant

A thermostat has a target temperature that people change with buttons. The heating system can work only with targets from 10 to 30 °C, so every Thermostat must keep this invariant:

10 <= target <= 30, at every moment that other code can see it.

Exercise L14.3 (LO-14.2, ★★, about 25 minutes)

Write Thermostat, with its invariant in the class’s docstring:

  • Thermostat() starts with a target of 20.0, and Thermostat(18.5) with 18.5.

  • set_target(value) sets a new target.

  • warmer(step=0.5) raises the target by step, and cooler(step=0.5) lowers it by step. Each returns the new target.

A target out of range, nan included, and a step that isn’t more than 0, raise ValueError with a message that says what was wrong, and leave the target as it was. So warmer() at 30 raises instead of going above 30.

The check below calls your thermostat’s methods 2,000 times with random arguments, some of them bad, and checks the invariant after every call.

4. Printing and comparing

Exercise L14.4 (LO-14.3, ★, about 15 minutes)

Wind holds a wind speed and the direction it blows from. Add two methods to it:

  • __repr__, so that Wind(12.0, "NW") shows as Wind(speed_kmh=12.0, direction='NW').

  • __eq__, so that two Wind objects are equal when both their speeds and their directions are equal. For anything that isn’t a Wind, return NotImplemented.

5. The same class as a dataclass

Exercise L14.5 (LO-14.2, LO-14.3, ★★, about 20 minutes)

Write WindReading as a frozen dataclass with three fields, each with a type hint, in this order: station, a string; speed_kmh, a float; and direction_deg, an int, the direction the wind blows from in degrees, where 0 is north and 90 is east. Give it a __post_init__ that raises ValueError unless the speed is from 0 to 500 and the direction from 0 to 359. Don’t write __init__, __repr__, or __eq__: the dataclass writes them.

6. Type hints

Exercise L14.6 (LO-14.4, ★★, about 20 minutes)

Add type hints to the parameters and return values of these three functions, and to the variable groups in by_station: a type checker can’t tell from {} alone what an empty dictionary will hold. Change nothing else.

  • gust_factor divides two speeds, which may be floats.

  • strongest returns the reading with the highest speed, or None for an empty list.

  • by_station returns a dictionary from each station’s name to a list of its readings.

Now predict what happens when each line below runs, before you run the next cell. For each, answer "runs" if Python runs it to the end, or "error" if it raises an exception.

gust_factor(40, 20)                              # h1
gust_factor("40", 20)                            # h2
strongest(["calm", "breezy"])                    # h3

Then answer h4: which of the three calls would mypy report, as a list of "h1", "h2", and "h3"?

Summary

  • A class bundles data, in attributes on self, with the methods that use and change it. Each instance has its own attributes, as long as __init__ creates them.

  • An invariant is kept by checking every argument in __init__ and in every method that changes the object, before changing anything. The thermostat’s check tried 2,000 calls and found the invariant true after each one.

  • __repr__ and __eq__ make objects readable and comparable, and a frozen dataclass writes both, with __init__ and a hash, from its fields.

  • Python doesn’t check type hints: h2 and h3 ran until an operation failed, inside the function. A type checker reports both calls before the program runs, which Module 18 sets up.