105. Property Decorators

Property decorators in Python are used to define getter, setter, and deleter methods for class attributes in a more readable and Pythonic way. Instead of manually defining methods like get_name() and set_name(), you can use the @property decorator to create getter methods and the @<property_name>.setter and @<property_name>.deleter decorators for setters and deleters, respectively.

Here are 10 Python snippets demonstrating how to use property decorators for managing class attributes.

1. Basic Property with Getter

class Person:
    def __init__(self, name):
        self._name = name
    
    @property
    def name(self):
        return self._name

# Usage
p = Person("Alice")
print(p.name)  # This calls the getter method

Explanation: The @property decorator is used to define the getter method for the name attribute.


2. Property with Setter

class Person:
    def __init__(self, name):
        self._name = name
    
    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if not value:
            raise ValueError("Name cannot be empty")
        self._name = value

# Usage
p = Person("Alice")
p.name = "Bob"  # This calls the setter method
print(p.name)

Explanation: The setter method is defined using @name.setter. It allows you to set a value for the name attribute, with validation.


3. Property with Deleter

Explanation: The @name.deleter decorator is used to define the method for deleting the name attribute. In this case, we print a message before deleting it.


4. Property with a Computed Value

Explanation: The area property calculates a value dynamically rather than storing it. It’s automatically updated based on the width and height.


5. Property with Cached Getter

Explanation: This example shows a computed property where the Fibonacci number is cached to optimize performance.


6. Setter with Validation

Explanation: The setter ensures that the age attribute cannot be set to a negative value.


7. Read-Only Property

Explanation: circumference is a read-only property derived from the radius.


8. Property with Logging

Explanation: The setter for celsius logs the change each time the temperature is set.


9. Private Attribute with Property Access

Explanation: A private attribute (_balance) is accessed and modified using the property decorators.


10. Class Property

Explanation: A class-level property is created using the @classmethod and @property decorators together. It tracks the total number of cars created.


Key Concepts:

  1. Getter (@property): Defines a method to access the value of an attribute.

  2. Setter (@property_name.setter): Defines a method to set the value of an attribute with validation or other logic.

  3. Deleter (@property_name.deleter): Defines a method to delete an attribute.

  4. Read-only Properties: Properties that can only be accessed but not modified.

  5. Validation: Properties can include validation logic to ensure data integrity.

  6. Caching/Optimization: You can cache values to improve performance, especially in computed properties.

  7. Private Attributes: Properties provide controlled access to private attributes, which cannot be directly accessed outside the class.

Using property decorators helps to keep the class interface clean and intuitive, while still encapsulating the internal logic.

Last updated