The `@property` Decorator: Clean Getters & Setters
`@property` turns a method into a read-only attribute getter. Pair it with `@name.setter` to validate incoming data without breaking dot syntax.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return (self._celsius * 9/5) + 32
t = Temperature(0)
print(t.fahrenheit) # 32.0 (Accessed like an attribute!)
# 6. The `@property` Decorator: Clean Getters & Setters `@property` turns a method into a read-only attribute getter. Pair it with `@name.setter` to validate incoming data without breaking dot syntax: ```python class Temperature: def __init__(self, celsius): self._celsius = celsius @property def fahrenheit(self): return (self._celsius * 9/5) + 32 t = Temperature(0) print(t.fahrenheit) # 32.0 (Accessed like an attribute!) ``` This ensures backward compatibility: Start with plain attributes (`self.price = 10`). If you later need to validate that price is positive, convert it to a `@property` without breaking external code using `obj.price`.