SyntaxStudy
Sign Up
Python The @property Decorator
Python Intermediate 4 min read

The @property Decorator

@property Decorator

@property lets you define a method that is accessed like an attribute. Use @name.setter and @name.deleter for full control.

Example
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
Pro Tip

@property is ideal for computed or validated attributes.