Python property decorator

Share Your Love

In Python property decorator is a built-in function that allows you to define methods that are accessed like attributes. It is used to create “getter,” “setter,” and “deleter” methods for managing attribute access and modification in a controlled manner. The property decorator helps in implementing the concept of encapsulation by providing a way to define computed or validated attributes.

The property decorator is typically used in conjunction with three methods:

  1. Getter method: This method retrieves the value of a property.
  2. Setter method: This method sets the value of a property.
  3. Deleter method: This method deletes a property.

Here’s an example that demonstrates the usage of the property decorator:

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

    def diameter(self):
        return 2 * self.radius

    def diameter(self, value):
        self.radius = value / 2

    def diameter(self):
        del self.radius

# Creating a Circle object
c = Circle(5)

# Accessing the diameter property
print(c.diameter)  # Output: 10

# Modifying the diameter property
c.diameter = 14
print(c.radius)  # Output: 7

# Deleting the diameter property
del c.diameter
print(c.radius)  # Raises an AttributeError: 'Circle' object has no attribute 'radius'

In the example above, the Circle class defines a radius attribute. The diameter property is defined using the @property decorator, which transforms the diameter() method into a read-only property. It allows accessing the diameter as an attribute without calling it as a method.

The @diameter.setter decorator is used to define the setter method for the diameter property. It is called when the property is assigned a new value. In this case, it updates the radius attribute based on the provided diameter value.

The @diameter.deleter decorator defines the deleter method for the diameter property. It is called when the property is deleted. In this example, it deletes the radius attribute.

By using the property decorator with its associated getter, setter, and deleter methods, you can control attribute access and modify the behavior of accessing or modifying properties in Python classes.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter