Properties, descriptors & immutability
P28.data-modelling.03 · Audience: guest, it-ml, language-pro · Prerequisites: Dunder methods & the data model
Attributes don't have to be plain slots. A property turns attribute access
into method calls (computed values, validation on set); a descriptor is the
reusable machinery behind properties, letting you factor a validation rule out
of one class and share it across many; and __slots__ trades per-instance
flexibility for memory and a fixed attribute set. Together they are how you make
an object correct by construction.
Ask the mentor about this module
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
Rung 1 — write a validating descriptor
Loading exercise…
Rung 2 — __slots__ and a computed property
Loading exercise…
The pay-off of immutability and validation is that whole classes of bug become
unrepresentable: a Temperature can never hold a value below absolute zero,
and an Account can never carry a negative balance, because the object refuses
to be built that way.
Where next?
Go up a level