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 14: Classes and objects

Objectives: LO-14.1, LO-14.2, LO-14.3, LO-14.4
Prerequisites: Module 8 and Module 12
Time: about 5.5 hours: 2 for this reading, 2 for Lab 14, and 1.5 for the practice

In Project 2, a reading was a dictionary, and the functions that worked on readings lived in a module beside it. Nothing stopped a reading from missing a key, or from holding a temperature of 75 °C, except the checks each function remembered to make. This module teaches you to define your own types, classes, which keep data and the functions that work on it together and can refuse to hold data that breaks their rules. It ends with dataclasses, which write the routine parts of a class for you, and type hints, which say what type each value should have.

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

Classes, instances, and methods

Every value in Python is an object, and every object has a type: type(3) is int, and type("Harbor") is str. A class defines a new type. Once it is defined, you call the class like a function to create objects of that type, its instances. Each instance has its own attributes, the named values it holds, and shares the class’s methods, the functions defined inside the class.

Save this as station.py:

class Station:
    """A weather station and the temperatures it has recorded."""

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

    def add(self, temp):
        """Record one temperature, in degrees Celsius."""
        self.temps.append(temp)

    def mean(self):
        """Return the mean of the recorded temperatures."""
        return sum(self.temps) / len(self.temps)


harbor = Station("Harbor")
hilltop = Station("Hilltop")
harbor.add(8.5)
harbor.add(11.0)
hilltop.add(4.0)
print(harbor.name, harbor.temps, harbor.mean())
print(hilltop.name, hilltop.temps, hilltop.mean())
print(type(harbor))
print(harbor)
Harbor [8.5, 11.0] 9.75
Hilltop [4.0] 4.0
<class '__main__.Station'>
<__main__.Station object at 0x717343678920>

Read it piece by piece:

A class bundles data with the functions that are allowed to change it. Compare the dictionary version, where mean would be a separate function, and any code could put anything into readings["temps"]. The class doesn’t stop other code from changing harbor.temps directly, but it gives the right way to change it a name, add, and one place to check what comes in.

Invariants: keeping an object valid

An invariant is a condition that must hold for every instance, at every moment that other code can see it. A class keeps its invariant by checking arguments in __init__, so that no instance starts invalid, and in every method that changes the instance, so that none becomes invalid. When a check fails, the method raises an exception, as Module 12 showed, and changes nothing.

A rain gauge holds rain up to its capacity. Its invariant is that the capacity is more than 0, and the level is from 0 up to the capacity. Save this as gauge.py:

class RainGauge:
    """A rain gauge that holds up to capacity_mm of rain.

    Invariant: 0 <= level_mm <= capacity_mm, and capacity_mm > 0.
    """

    def __init__(self, capacity_mm):
        if not capacity_mm > 0:
            raise ValueError(f"capacity must be more than 0 mm, not {capacity_mm}")
        self.capacity_mm = capacity_mm
        self.level_mm = 0.0

    def add(self, rain_mm):
        """Add rain, and return how much spilled over the top."""
        if not rain_mm >= 0:
            raise ValueError(f"rain can't be negative: {rain_mm}")
        room = self.capacity_mm - self.level_mm
        if rain_mm > room:
            self.level_mm = self.capacity_mm
            return rain_mm - room
        self.level_mm += rain_mm
        return 0.0

    def empty(self):
        """Empty the gauge, and return how much rain it held."""
        level = self.level_mm
        self.level_mm = 0.0
        return level

And this as gauge_demo.py, in the same folder:

from gauge import RainGauge

gauge = RainGauge(50.0)
print(gauge.add(12.5), gauge.level_mm)
print(gauge.add(40.0), gauge.level_mm)
print(gauge.empty(), gauge.level_mm)
gauge.add(-3)
0.0 12.5
2.5 50.0
50.0 0.0
Traceback (most recent call last):
  File "/home/ada/py101/m14/gauge_demo.py", line 7, in <module>
    gauge.add(-3)
  File "/home/ada/py101/m14/gauge.py", line 16, in add
    raise ValueError(f"rain can't be negative: {rain_mm}")
ValueError: rain can't be negative: -3

Python doesn’t stop code outside the class from writing gauge.level_mm = -5, which breaks the invariant without any check. Two conventions limit this. Code outside a class reads attributes but changes the object only through its methods. And a name that starts with one underscore, such as self._level_mm, tells other programmers that the attribute is internal to the class and may change. Python enforces neither convention; they work because programmers follow them.

Printing and comparing objects

Two special methods control how an object prints and how it compares. Like __init__, Python calls them for you.

Add both to RainGauge, after __init__:

    def __repr__(self):
        return f"RainGauge(capacity_mm={self.capacity_mm!r}, level_mm={self.level_mm!r})"

    def __eq__(self, other):
        if not isinstance(other, RainGauge):
            return NotImplemented
        return (self.capacity_mm, self.level_mm) == (other.capacity_mm, other.level_mm)
a = RainGauge(50.0)
b = RainGauge(50.0)
print(a)
print([a, b])
print(a == b, a is b, a == 50.0)
RainGauge(capacity_mm=50.0, level_mm=0.0)
[RainGauge(capacity_mm=50.0, level_mm=0.0), RainGauge(capacity_mm=50.0, level_mm=0.0)]
True False False

Defining __eq__ has one side effect: instances can no longer go in a set or be dictionary keys. {RainGauge(1.0)} raises TypeError: unhashable type: 'RainGauge'. Python requires that equal objects have equal hash values, the numbers sets and dictionaries use to find items, and it can’t guarantee that for an object whose attributes change. A frozen dataclass, next, solves this for values that never change.

Dataclasses

Many classes mostly hold data, and their __init__, __repr__, and __eq__ repeat the list of attributes three times. The dataclasses module writes those three methods for you from one list of fields, each with a type annotation. Save this as reading.py:

from dataclasses import dataclass
from datetime import date


@dataclass(frozen=True)
class Reading:
    """One day's weather at one station."""

    station: str
    day: date
    temp_c: float
    rain_mm: float = 0.0

    def __post_init__(self):
        if not -90 <= self.temp_c <= 60:
            raise ValueError(f"temp_c must be from -90 to 60, not {self.temp_c}")
        if not self.rain_mm >= 0:
            raise ValueError(f"rain_mm can't be negative: {self.rain_mm}")

Save this as reading_demo.py, and run it:

from datetime import date

from reading import Reading

first = Reading("Harbor", date(2026, 11, 2), 8.5)
again = Reading("Harbor", date(2026, 11, 2), 8.5, rain_mm=0.0)
print(first)
print(first == again, first.temp_c)
print({first, again})
first.temp_c = 30.0
Reading(station='Harbor', day=datetime.date(2026, 11, 2), temp_c=8.5, rain_mm=0.0)
True 8.5
{Reading(station='Harbor', day=datetime.date(2026, 11, 2), temp_c=8.5, rain_mm=0.0)}
Traceback (most recent call last):
  File "/home/ada/py101/m14/reading_demo.py", line 10, in <module>
    first.temp_c = 30.0
    ^^^^^^^^^^^^
  File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'temp_c'

A field whose default is a list or dictionary needs field(default_factory=list), from dataclasses, which makes a new list for each instance. temps: list[float] = [] raises ValueError when the class is defined, because one list shared by every instance is almost always a bug.

Choose a dataclass when the class is mostly its data, and a hand-written class when its methods must control every change, as RainGauge.add does. A dataclass can have methods too.

Type hints

The annotations in a dataclass, such as temp_c: float, are type hints: notes that say what type a value should have. Functions can have them too, on each parameter and, after ->, on the return value:

def mean_temp(readings: list[Reading]) -> float:
    """Return the mean temperature of readings, which must not be empty."""
    return sum([reading.temp_c for reading in readings]) / len(readings)


def warmest(readings: list[Reading]) -> Reading | None:
    """Return the warmest reading, or None if there are none."""
    if not readings:
        return None
    return max(readings, key=lambda reading: reading.temp_c)

What Python checks, and what it leaves to a type checker

Python stores the hints but doesn’t check them while the program runs. Save this as hints.py. It has the Reading dataclass without rain_mm or __post_init__, the two functions above, and three lines that use them:

from dataclasses import dataclass
from datetime import date


@dataclass(frozen=True)
class Reading:
    station: str
    day: date
    temp_c: float


def mean_temp(readings: list[Reading]) -> float:
    """Return the mean temperature of readings, which must not be empty."""
    return sum([reading.temp_c for reading in readings]) / len(readings)


def warmest(readings: list[Reading]) -> Reading | None:
    """Return the warmest reading, or None if there are none."""
    if not readings:
        return None
    return max(readings, key=lambda reading: reading.temp_c)


week = [Reading("Harbor", date(2026, 11, 2), 8.5), Reading("Harbor", "2026-11-03", 11)]
print(mean_temp(week))
print(warmest(week).station)
print(mean_temp("Harbor"))
9.75
Harbor
Traceback (most recent call last):
  File "/home/ada/py101/m14/hints.py", line 27, in <module>
    print(mean_temp("Harbor"))
          ^^^^^^^^^^^^^^^^^^^
  File "/home/ada/py101/m14/hints.py", line 14, in mean_temp
    return sum([reading.temp_c for reading in readings]) / len(readings)
                ^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'temp_c'

The second reading’s day is a string, against its hint, and nothing complains: the dataclass stores whatever it gets. The program fails only at the last line, and inside mean_temp, not at the call that was wrong.

A type checker reads the code and its hints without running it, and reports every place where a value can’t have the type a hint promises. mypy is the most widely used one for Python; Module 18 installs it. On hints.py, it reports:

hints.py:24: error: Argument 2 to "Reading" has incompatible type "str"; expected "date"  [arg-type]
hints.py:26: error: Item "None" of "Reading | None" has no attribute "station"  [union-attr]
hints.py:27: error: Argument 1 to "mean_temp" has incompatible type "str"; expected "list[Reading]"  [arg-type]
Found 3 errors in 1 file (checked 1 source file)

All three are real problems, found before the program ran. The second is one no test of this data would show: warmest(week) happened to return a reading, but for an empty list it returns None, and None.station would crash.

The division of labor is:

CheckedBy whomWhen
Types of values passed and returned, as the hints stateA type checker, such as mypyBefore the program runs, on every path through the code
Operations a value doesn’t support, such as "warm" <= 60PythonWhile the program runs, only on the lines that run
Rules about values, such as a temperature from -90 to 60Your own checks, in __init__ or __post_init__While the program runs

Hints also document a function for every reader, and editors such as VS Code use them to offer the right methods as you type.

Common misconceptions

MisconceptionWhat’s trueAn example that breaks it
self is a keyword that Python adds by itselfIt is an ordinary first parameter, which you must writedef add(temp): in a class makes station.add(8.5) raise TypeError: Station.add() takes 1 positional argument but 2 were given
name = name in __init__ stores the nameWithout self., it sets a local variable that disappearsStation("Harbor").name raises AttributeError: 'Station' object has no attribute 'name'
An attribute assigned in the class body belongs to each instanceIt belongs to the class, and every instance shares itWith temps = [] under class Station:, harbor.add(8.5) makes hilltop.temps print [8.5]
Two objects with the same attributes are ==Without __eq__ (or a dataclass), == compares identityTwo RainGauge(50.0) objects without __eq__ aren’t equal
Python enforces type hintsPython ignores them while running; a type checker reads themReading("Harbor", "2026-11-03", 11) runs, though day should be a date

Summary

Self-check

  1. What does this print, and why?

    class Counter:
        def __init__(self):
            self.count = 0
    
        def click(self):
            self.count += 1
            return self.count
    
    
    a = Counter()
    b = Counter()
    a.click()
    a.click()
    print(a.click(), b.click(), a.count)

    Answer

    3 1 3. Each instance has its own count. a is clicked three times in all, and the third call returns 3; b is clicked once.

  2. A Countdown has a length in seconds and the seconds remaining, which start at length. Its methods are tick(seconds), which counts down, reset(), and is_done(). State its invariant, and say which methods must check something.

    Answer

    Invariant: length > 0, and 0 <= remaining <= length. __init__ must check length. tick must refuse a negative seconds, and must not take remaining below 0: it either raises or stops at 0, a choice its docstring should state. reset sets remaining to length, which keeps the invariant without a check, and is_done only reads.

  3. Why does RainGauge.__eq__ return NotImplemented for an other that isn’t a RainGauge, instead of False?

    Answer

    NotImplemented lets Python ask the other object, which may know how to compare itself with a RainGauge. If neither knows, Python falls back to identity, so the result is still False for gauge == 50.0. Returning False would answer for the other type without asking it.

  4. Write a frozen dataclass Point with float fields x and y, and say what Point(1, 2) == Point(1.0, 2.0) and {Point(0, 0), Point(0, 0)} give.

    Answer

    from dataclasses import dataclass
    
    
    @dataclass(frozen=True)
    class Point:
        x: float
        y: float

    Point(1, 2) == Point(1.0, 2.0) is True, because 1 == 1.0 and 2 == 2.0. The set holds one point: the two are equal and, being frozen, have equal hashes.

  5. def area(width: float, height: float) -> float: return width * height. What does area("ab", 3) do when it runs, and what would mypy say?

    Answer

    It runs and returns "ababab", because Python doesn’t check hints and "ab" * 3 repeats the string. mypy reports that argument 1 to area has incompatible type str; expected float, without running anything.

Further reading