Curriculum
In Python, the @property
decorator is a convenient way to create a getter method for a class attribute. It allows us to define a method that is called when we access the attribute, as if it were a normal attribute, without explicitly calling the method.
Here’s an example of how the @property
decorator can be used to create a getter for a class attribute:
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 must be non-negative") self._radius = value @property def diameter(self): return self._radius * 2 @diameter.setter def diameter(self, value): if value < 0: raise ValueError("Diameter must be non-negative") self._radius = value / 2 @property def area(self): return 3.14 * self._radius ** 2 c = Circle(5) print(c.radius) # 5 print(c.diameter) # 10 print(c.area) # 78.5 c.radius = 7 print(c.diameter) # 14 print(c.area) # 153.86 c.diameter = 20 # Sets radius to 10 print(c.radius) # 10 print(c.area) # 314.0 c.radius = -1 # ValueError: Radius must be non-negative
In this example, we define a Circle
class with a radius
attribute, and three methods that calculate the diameter
, area
, and validate the user input for radius
attribute. We use the @property
decorator to define getter methods for the radius
, diameter
, and area
attributes.
We also use the @<attribute_name>.setter
decorator to define setter methods for the radius
and diameter
attributes. The setter methods validate the user input for the radius
and diameter
attributes, and update the radius
attribute accordingly.
When we create a Circle
object c
with a radius of 5, we can use the radius
, diameter
, and area
attributes to get the corresponding values. The @property
decorator allows us to define a simple and intuitive interface for working with the Circle
object, without explicitly calling the getter methods.
When we set the radius
or diameter
attributes, the corresponding setter methods are called to validate the user input and update the radius
attribute accordingly.
Using the @property
decorator can be a useful way to define a simple and intuitive interface for working with class attributes, especially when the attributes require custom logic for access and modification.