Objects and classes
A class is how you give a value its own behaviour — so that adding two amounts of money checks the currency, and comparing them compares what they mean rather than where they live in memory. These exercises are about the handful of dunder methods that make an object feel like part of the language instead of a bag of attributes.
—Exercises
10 exercises
The class you barely have to write
@dataclass, generated __eq__ and __repr__
~18 min
A Stack that knows how long it is
__len__ and free truthiness, private attributes
~20 min
Settings nobody can change behind your back
frozen dataclass, hashable values
~22 min
Keys that do not care about capitals
__getitem__ and friends, normalising at the boundary
~24 min
Stock that cannot go negative
methods that guard state, zero is not a stock level
~24 min
A Money value that behaves like one
__eq__ and NotImplemented, __add__
~25 min
A Temperature that cannot be impossible
@property, computed attributes
~25 min
An object you can loop over twice
__iter__, iterable versus iterator
~24 min
A set that keeps the order you added things
operator dunders, returning new objects
~28 min
Versions that sort like versions
tuple comparison, functools.total_ordering
~30 min