How to Use Property Decorator in Python: Simple Guide
@property decorator lets you define methods that act like attributes, allowing controlled access to instance variables. You use @property for the getter method, and @.setter to define the setter method for the same attribute.Syntax
The @property decorator is placed above a method to make it behave like a read-only attribute. To allow setting a value, you define a setter method with @property_name.setter. Optionally, you can add a deleter with @property_name.deleter.
- Getter: Method to get the attribute value.
- Setter: Method to set the attribute value.
- Deleter: Method to delete the attribute.
class MyClass: @property def attribute(self): # getter method return self._attribute @attribute.setter def attribute(self, value): # setter method self._attribute = value @attribute.deleter def attribute(self): # deleter method del self._attribute
Example
This example shows a class with a private variable _temperature and a property temperature that controls access to it. The setter checks that the temperature is not below absolute zero.
class Celsius: def __init__(self, temperature=0): self._temperature = temperature @property def temperature(self): return self._temperature @temperature.setter def temperature(self, value): if value < -273.15: raise ValueError("Temperature below -273.15 is not possible") self._temperature = value c = Celsius() c.temperature = 25 print(c.temperature) try: c.temperature = -300 except ValueError as e: print(e)
Common Pitfalls
One common mistake is forgetting to use the @property decorator on the getter method, which means the attribute won't behave like a property. Another is not using the correct setter decorator name (@property_name.setter), causing errors. Also, directly accessing the private variable outside the class defeats the purpose of using properties.
class Wrong: def temperature(self): # Missing @property return self._temperature def temperature(self, value): # This does not set a property setter self._temperature = value # Correct way: class Right: @property def temperature(self): return self._temperature @temperature.setter def temperature(self, value): self._temperature = value
Quick Reference
| Decorator | Purpose |
|---|---|
| @property | Defines the getter method to access the attribute. |
| @ | Defines the setter method to modify the attribute. |
| @ | Defines the deleter method to delete the attribute. |