Manage calculated attributes and validated assignments with property decorators.
How It Works
@property exposes a method as a read-style attribute. A matching @name.setter validates assignments, and @name.deleter defines optional deletion behavior; each operation is explicit.
Read-only properties need only the getter; mutable properties should protect invariants.
Step-by-Step Example
class Thermostat:
def __init__(self, target_temperature):
self.target_temperature = target_temperature
@property
def target_temperature(self):
return self._target_temperature
@target_temperature.setter
def target_temperature(self, value):
if not -20 <= value <= 50:
raise ValueError("Temperature out of range")
self._target_temperature = value
@target_temperature.deleter
def target_temperature(self):
del self._target_temperature
thermostat = Thermostat(22)
print(thermostat.target_temperature)
del thermostat.target_temperature
print(hasattr(thermostat, "_target_temperature"))
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
22
False
Where This Fits in a Real Program
Before putting the technique into a larger program, identify the required inputs and which results are returned. Choose what should happen with invalid or missing data, and test a small valid case and a failing case independently.
Practice: Try It Yourself
Add a temperature property that rejects invalid values.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Accidentally assigning to the same property from its setter and causing infinite recursion.
- Assuming a property automatically provides a setter or deleter without defining one.
Key Takeaways
- Manage calculated attributes and validated assignments with property decorators.
- @property exposes a method as a read-style attribute.
- Read-only properties need only the getter; mutable properties should protect invariants.