Full answer
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 = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(25)
print(t.fahrenheit)
t.celsius = 100
print(t.fahrenheit)
for action in (lambda: setattr(t, "celsius", -300), lambda: setattr(t, "fahrenheit", 50)):
try:
action()
except (ValueError, AttributeError) as e:
print(type(e).__name__, e)Output:
77.0
212.0
ValueError below absolute zero
AttributeError property 'fahrenheit' of 'Temperature' object has no settercelsius stores the value in _celsius after checking it, so assigning -300 raises a ValueError with a clear message. fahrenheit is computed from the stored value every time it is read, so it can never go stale. Assigning to fahrenheit fails with an AttributeError because no setter exists; the exact message comes from Python 3.13.
Why properties matter: a class can start with a plain public attribute and later switch to a property with validation without changing any calling code. That makes Java-style get_x() and set_x() methods unnecessary in Python.
Keep properties cheap; callers expect attribute access to be fast and free of side effects. For expensive values, functools.cached_property computes once per instance.
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 = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(25)
print(t.fahrenheit)
t.celsius = 100
print(t.fahrenheit)
for action in (lambda: setattr(t, "celsius", -300), lambda: setattr(t, "fahrenheit", 50)):
try:
action()
except (ValueError, AttributeError) as e:
print(type(e).__name__, e)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- @property makes computed attributes
- Setters validate assignments
- No setter means read-only
- Switch from attributes to properties without breaking callers
- cached_property for expensive values
Common mistakes
- Doing slow work inside a property
- Storing the value under the same name as the property, causing recursion
Follow-ups
- How does cached_property differ from property?
- What is a descriptor?
Tips
- Store the value under a different attribute name