search

What is the use of the "property" decorator in Python?

The **property** decorator in Python is used to define a method as a "getter" for a class property. The property can be accessed like an instance attribute, but its value is computed by calling the getter method. The property decorator can also be used to define "setter" and "deleter" methods, which allow for setting and deleting the value of the property, respectively.

Here is an example of how you can use the **property** decorator:

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

c = Circle(5)
print(c.radius) # 5
c.radius = 10
print(c.radius) # 10

In this example, the **radius** method is decorated with the **property** decorator, making it a getter method for the **radius** property. The **radius.setter** decorator is used to define a setter method for the property.

Related Questions You Might Be Interested