Property Decorators in Python Made Easy
Property decorators in Python allow you to define getter, setter, and deleter methods for a class attribute. They are used to control access to the attribute and can be useful in many cases, such as data validation, property-based methods, and more. The @property decorator is used to define a getter method, the @attribute_name.setter decorator is used to define a setter method, and the @attribute_name.deleter decorator is used to define a deleter method.
Here are a few examples of property decorators in Python:
Example 1:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
first_circle = Circle(-5)
second_circle = Circle(5)
print(first_circle.radius) # Output: -5
print(second_circle.radius) # Output: 5
first_circle.radius = 6
print(first_circle.radius) # Output: 6
second_circle.radius = -57
print(second_circle.radius)
'''
Output: raceback (most recent call last):
File "<string>", line 22, in <module>
File "<string>", line 12, in radius
ValueError: Radius cannot be negative */
'''
In the above example, the Circle class has an radius
attribute that can be set only to a positive value. If a negative value is passed, a ValueError will be raised. The @property
decorator allows us to access the radius
attribute directly, without having to use a method. The @radius.setter
decorator allows us to set the radius
attribute, and the setter method is used to validate the input.
Example 2:
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
self._celsius = value
@property
def fahrenheit(self):
return (self._celsius * 1.8) + 32
In this example, the Temperature class has two attributes, celsius
and fahrenheit
. The celsius
the attribute can be set and retrieved directly, while the fahrenheit
attribute can only be retrieved. The fahrenheit
property is calculated based on the celsius
attribute using the formula (celsius * 1.8) + 32
.