property() Function in Python

Python property() Function

The property() function in Python is a built-in function that allows you to create read-only properties for class attributes. It is often used as a decorator to define getter, setter, and deleter methods for a specific attribute. Properties are useful when you want to encapsulate attribute access and provide additional control over how the attribute is accessed, modified, or deleted.

The property() function takes up to four arguments, but in most cases, only three are used:

property(fget=None, fset=None, fdel=None, doc=None)
  • fget: The function used to get the value of the property (getter). It should take an instance of the class as its argument and return the property value.

  • fset: The function used to set the value of the property (setter). It should take an instance of the class and the new value as its arguments and handle the assignment of the property.

  • fdel: The function used to delete the property (deleter). It should take an instance of the class as its argument and handle the deletion of the property.

  • doc: An optional string providing documentation for the property.

Let's see an example to better understand how to use the property() function:

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @property
    def diameter(self):
        return 2 * self._radius

    @property
    def area(self):
        return 3.14 * self._radius ** 2

    @radius.setter
    def radius(self, value):
        if value >= 0:
            self._radius = value
        else:
            raise ValueError("Radius cannot be negative.")

    @radius.deleter
    def radius(self):
        print("Deleting the circle...")
        del self._radius

# Using the Circle class
c = Circle(5)
print(c.radius)  # Output: 5
print(c.diameter)  # Output: 10
print(c.area)  # Output: 78.5

c.radius = 7
print(c.diameter)  # Output: 14
print(c.area)  # Output: 153.86

del c.radius  # Output: Deleting the circle...

In this example, we defined a Circle class with three read-only properties: radius, diameter, and area. The radius property has a setter method to ensure that the radius is non-negative. When we try to delete the radius property, the custom deleter method is called.

Using the property() function, you can create more controlled and flexible attributes in your classes, providing a cleaner and more intuitive interface to interact with objects.