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:
class Station:starts the definition. Class names useCapitalizedWords, which tells a reader thatStation("Harbor")creates an object rather than calling an ordinary function.Station("Harbor")creates a new, empty instance, then calls__init__on it with"Harbor".__init__(two underscores on each side) is the initializer: Python calls it for you to set up each new instance, and it returns nothing.selfis the instance itself. Every method receives it as its first parameter, and Python fills it in:harbor.add(8.5)callsStation.add(harbor, 8.5). That is whyaddtakes two parameters but is called with one argument.self.name = namecreates an attribute on this instance.harbor.nameandhilltop.nameare different values, and so areharbor.tempsandhilltop.temps, two separate lists.The last line prints Python’s default description of an instance: its class and the address of the object in memory, which changes from run to run. The section on
__repr__replaces it with something useful.
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 levelAnd 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: -3The docstring states the invariant, so a reader knows what every method must protect.
The checks are written as “accept only what is in range”,
not capacity_mm > 0andnot rain_mm >= 0, so thatnan, which fails every comparison, is refused too.adddecides what happens at the edge: rain that doesn’t fit spills, the gauge stays full, and the method returns the spill. Every path through it leaves the level from 0 to the capacity.RainGauge(0)raisesValueError: capacity must be more than 0 mm, not 0, so an invalid gauge never exists.
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.
__repr__returns a string that describes the object, for programmers. Python uses it when it shows the object in the interactive prompt, in a list, or in a traceback, andprintand f-strings use it too unless the class also defines__str__. The convention is to return text that looks like the call that would create an equal object.__eq__(self, other)decides what==means. Without it,a == bis the same asa is b: two instances are equal only if they are the same object, even if every attribute matches.
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!rinside an f-string uses each value’s ownrepr, so a string attribute would appear in quotes, as it would in a call.isinstance(other, RainGauge)isTruewhenotheris aRainGauge. For anything else,__eq__returns the special valueNotImplemented, which tells Python to try the other object’s__eq__and, if that doesn’t know either, to fall back to identity. That is whya == 50.0isFalseinstead of an error.a == bis nowTrue, buta is bis stillFalse: they are two objects with equal values.isasks whether two names refer to the same object, and==asks whether two objects are equal. Useismainly to compare withNone, as inif result is None:.
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.0Reading(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'@dataclassis a decorator: the line above a definition that changes it. Module 16 shows how decorators work; here it is enough that@dataclassreads the fields and adds the methods.Each field is a name, a colon, and a type:
station: str. A field with a value, such asrain_mm: float = 0.0, has a default, and fields with defaults come after those without.The generated
__init__takes the fields as parameters, in order, and the generated__repr__and__eq__use all of them. Two readings with equal fields are equal, asfirst == againshows.frozen=Truemakes instances immutable: assigning to a field raisesFrozenInstanceError. Because a frozen instance can’t change, the dataclass also gives it a hash, so readings can go in a set, wherefirstandagaincount once.__post_init__runs at the end of the generated__init__. Put the invariant’s checks there:Reading("Harbor", date(2026, 11, 2), 75)raisesValueError: temp_c must be from -90 to 60, not 75.
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)list[Reading]is a list ofReadingobjects, anddict[str, float]would be a dictionary from strings to floats.Reading | Nonemeans “aReadingorNone”. It warns every caller to handle theNone.floataccepts aninttoo: a type checker lets11stand where11.0is expected.
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:
| Checked | By whom | When |
|---|---|---|
| Types of values passed and returned, as the hints state | A type checker, such as mypy | Before the program runs, on every path through the code |
Operations a value doesn’t support, such as "warm" <= 60 | Python | While the program runs, only on the lines that run |
| Rules about values, such as a temperature from -90 to 60 | Your 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¶
| Misconception | What’s true | An example that breaks it |
|---|---|---|
self is a keyword that Python adds by itself | It is an ordinary first parameter, which you must write | def 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 name | Without self., it sets a local variable that disappears | Station("Harbor").name raises AttributeError: 'Station' object has no attribute 'name' |
| An attribute assigned in the class body belongs to each instance | It belongs to the class, and every instance shares it | With 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 identity | Two RainGauge(50.0) objects without __eq__ aren’t equal |
| Python enforces type hints | Python ignores them while running; a type checker reads them | Reading("Harbor", "2026-11-03", 11) runs, though day should be a date |
Summary¶
A class defines a type. Calling it creates an instance and runs
__init__, which sets the instance’s attributes onself. Methods are functions in the class, and Python passes the instance to them asself.An invariant is a condition every instance must meet. Check arguments in
__init__and in every method that changes the object, raise an exception when a check fails, and state the invariant in the class’s docstring.__repr__describes an object for programmers, and__eq__decides what==means; returnNotImplementedfor types you don’t compare with.@dataclasswrites__init__,__repr__, and__eq__from annotated fields.frozen=Truemakes instances immutable and hashable, and__post_init__holds the checks.Type hints say what each value should be. Python doesn’t check them while running; a type checker such as mypy checks them before the program runs.
Self-check¶
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 owncount.ais clicked three times in all, and the third call returns 3;bis clicked once.A
Countdownhas alengthin seconds and the secondsremaining, which start atlength. Its methods aretick(seconds), which counts down,reset(), andis_done(). State its invariant, and say which methods must check something.Answer
Invariant:
length > 0, and0 <= remaining <= length.__init__must checklength.tickmust refuse a negativeseconds, and must not takeremainingbelow 0: it either raises or stops at 0, a choice its docstring should state.resetsetsremainingtolength, which keeps the invariant without a check, andis_doneonly reads.Why does
RainGauge.__eq__returnNotImplementedfor anotherthat isn’t aRainGauge, instead ofFalse?Answer
NotImplementedlets Python ask the other object, which may know how to compare itself with aRainGauge. If neither knows, Python falls back to identity, so the result is stillFalseforgauge == 50.0. ReturningFalsewould answer for the other type without asking it.Write a frozen dataclass
Pointwith float fieldsxandy, and say whatPoint(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: floatPoint(1, 2) == Point(1.0, 2.0)isTrue, because1 == 1.0and2 == 2.0. The set holds one point: the two are equal and, being frozen, have equal hashes.def area(width: float, height: float) -> float: return width * height. What doesarea("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" * 3repeats the string. mypy reports that argument 1 toareahas incompatible typestr; expectedfloat, without running anything.
Further reading¶
Allen B. Downey, Think Python, 3rd edition, chapters 14, Classes and Functions, 15, Classes and Methods, and 16, Classes and Objects. Classes for times, points, and rectangles, with more on copying objects and on identity and equality.
The Python Tutorial, chapter 9, Classes, sections 9.3 and 9.4. How Python finds an attribute, and why instance and class attributes differ.
The
dataclassesdocumentation. Every option of@dataclassandfield, includingorder=True, which adds<and>.The mypy documentation’s Getting started, and Static Typing with Python. What a type checker can check, and how to write hints for lists, dictionaries,
None, and your own classes.