@property Decorator
@property lets you define a method that is accessed like an attribute. Use @name.setter and @name.deleter for full control.
@property lets you define a method that is accessed like an attribute. Use @name.setter and @name.deleter for full control.
class Temperature:
def __init__(self, celsius):
self._c = celsius
@property
def fahrenheit(self):
return self._c * 9/5 + 32
@fahrenheit.setter
def fahrenheit(self, f):
self._c = (f - 32) * 5/9
t = Temperature(0)
print(t.fahrenheit) # 32.0
t.fahrenheit = 212
print(t._c) # 100.0
@property is ideal for computed or validated attributes.