Module 4: Pythonic Object Design
Properties and Managed Attributes
Properties and Managed Attributes
Properties preserve attribute-style access while adding validation, computation, or compatibility behind the interface. They let a simple public attribute evolve without forcing callers into getter and setter methods.
Module: Module 4: Pythonic Object Design
Core mental model
This lesson is built around four connected ideas. Read them as a decision framework, then prove each one with the walkthrough.
- A property getter computes or controls reads.
- A setter validates assignments before updating internal state.
- __getattr__ handles only missing attributes while __getattribute__ intercepts every access.
- Dynamic attribute hooks should be used sparingly because they obscure control flow.
Walkthrough
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = float(value)
@property
def fahrenheit(self):
return self.celsius * 9 / 5 + 32Initialization uses the public setter so one validation path protects all assignments. fahrenheit is derived and therefore read-only unless the design explicitly defines reverse conversion.
Hands-on lab
Evolve a public duration_seconds attribute into a validated property without changing caller syntax. Add a derived minutes property and tests for boundary values.
What to watch for
- A property that performs slow IO makes ordinary attribute access surprising.
- Recursively assigning the public property inside its setter causes infinite recursion.
- __getattribute__ mistakes can break all attribute access.
Engineering checklist
- Connect the lesson's mental model to the choices made in the walkthrough.
- Test the normal case, an empty or boundary case, and one invalid case.
- Keep external input, side effects, and reusable logic in clearly separated layers.
- Prefer the clearest correct implementation before optimizing or generalizing it.
Completion check
You can implement the lab without copying the example, explain the core concepts in your own words, and show tests or terminal output that demonstrate the expected and failure paths.