Objects that guard their own limits
A motor is rated to 3,000 rpm. Fifteen different parts of the code set its speed. How do you make sure none of them ever asks for 3,500?
About 35 min · 3 goals · Checked by automated tests
1.Why should I care?
An invariant is a rule that must always be true for an object: speed never exceeds the rating, stock never goes negative. If every change goes through methods that enforce the rule, you only have to get it right in one place.
- ◇ Write methods that change an object's state only in ways that keep a rule (an invariant) true.
- ◇ Explain why callers should use methods rather than setting attributes directly.
- ◇ Test an object's invariant, including its limits.
2.Discover
In the Code Lab, build the Motor class from the worked example. Call set_speed with 1500, 4000 and −200 and print speed each time. Then write motor._rpm = 9999 directly and print again. Add a test that would catch the bypass in a code review.
Can't use the interactive? Read a description instead
The Code Lab activity can be done on paper: a Motor rated 3000 rpm receives requests 1500, 4000 and −200 through set_speed and reports 1500, 3000 and 0. Assigning to the read-only rpm property raises AttributeError, while writing to the internal _rpm attribute bypasses the rule, which is why the convention and tests matter.
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
With the worked example's Motor('arm', 2400), what does set_speed(2650) return?
4.Apply it
Finish the inventory Part class: quantity is read through a property, withdraw(n) and restock(n) refuse invalid requests, and a test function tries at least six sequences of calls and asserts quantity ≥ 0 after each.
5.Understand
State changes go through methods
A Motor stores its speed in self._rpm. The method set_speed(rpm) clamps the request and is the only intended way in. Every caller gets the safety rule for free, and if the rule changes you edit one method.
Read through a property
Python's @property lets callers read motor.rpm like an attribute while it is really a method. Without a setter, motor.rpm = 3500 raises AttributeError, so the invariant can't be bypassed by accident through the public name.
Test the rule, not the code
Write tests from the invariant: after any sequence of calls, 0 ≤ rpm ≤ max_rpm. Test inside, both limits, above, below and a negative request. These tests stay valid however you rewrite the inside of the class.
Explain it another way
A thermostat lets you turn the dial, but the boiler has its own safety cut-out that you can't set past. Methods are the dial; the invariant is the cut-out.
Python has no truly private attributes. A single leading underscore signals 'internal'; @property creates read-only access; a @rpm.setter could validate assignments instead. Encapsulation in Python is a contract between programmers, backed by tests.
Motor controller firmware enforces current and speed limits inside the driver itself, not in every piece of code that requests motion, so a bug elsewhere can't overdrive the motor.
Worked example 1
A motor object that can never be set outside its rating.
class Motor:
def __init__(self, name, max_rpm):
if max_rpm <= 0:
raise ValueError("max_rpm must be positive")
self.name = name
self.max_rpm = max_rpm
self._rpm = 0
@property
def rpm(self):
return self._rpm
def set_speed(self, rpm):
"""Request a speed; it is clamped to [0, max_rpm]. Returns the speed set."""
self._rpm = max(0, min(rpm, self.max_rpm))
return self._rpm
m = Motor("left wheel", 3000)
print(m.set_speed(1500), m.set_speed(4000), m.set_speed(-200)) # 1500 3000 0
try:
m.rpm = 3500
except AttributeError:
print("rpm is read-only; use set_speed")Common mix-ups
- An underscore makes an attribute private.
✓ It's a convention. Python still allows access; tests and code review enforce it. - Validation belongs in every caller.
✓ Put it in the object's methods once. Callers then can't forget it.
6.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 2
Which is an invariant for an inventory Part object?
Practice 3
Motor defines rpm with @property and no setter. What does m.rpm = 3500 do?
Practice 4
part.withdraw(5) is called when quantity is 3. What should a well-designed method do?
Practice 5
Which test best checks Motor's invariant?
7.Predict
Motor has max_rpm = 3000 and a method set_speed(rpm) that clamps to [0, max_rpm]. Somewhere, code writes motor.rpm = 3500 directly. What is motor.rpm afterwards?
Guess first. Being wrong here is how the surprise works.
8.Reflect
9.Go further
- Python docs: property ↗How property creates managed attributes with getters and setters.
Concepts: Classes and objects · Testing and debugging