Protect the rules, not just the fields.
Use a property when reading or changing state needs a consistent rule.
01 The idea
A property presents method-backed behaviour through attribute syntax. It is useful when an object must enforce a rule every time a value is changed. Keep the public attribute meaningful and the underlying storage private by convention. Prefer straightforward public fields until there is an actual invariant or computed value to manage.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
class Battery:
def __init__(self, percent):
self.percent = percent
@property
def percent(self):
return self._percent
@percent.setter
def percent(self, value):
if type(value) is not int or not 0 <= value <= 100:
raise ValueError("percent must be an integer from 0 to 100")
self._percent = value
battery = Battery(70)
battery.percent = 85
print(battery.percent)85
03 Under the hood
- 1
The initializer goes through the public setter, so initial state and later updates follow the same rule.
- 2
The getter reads _percent, avoiding recursive access through self.percent. A leading underscore communicates an internal implementation detail; it is not a security boundary.
- 3
Validation keeps the object’s state meaningful. If expensive work or external I/O is involved, an explicit method may be clearer than hiding it behind attribute access.
04 Your turn, builder
Try setting a battery to 101 and show a deliberate validation response.
Reveal one possible solution +
class Battery:
def __init__(self):
self._percent = 50
@property
def percent(self):
return self._percent
@percent.setter
def percent(self, value):
if not 0 <= value <= 100:
raise ValueError("Out of range")
self._percent = value
try:
battery = Battery()
battery.percent = 101
except ValueError as error:
print(error)05 Check your signal
What should a property setter preserve?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.