What is the purpose of the @property decorator in Python OOP?

What is the purpose of the @property decorator in Python OOP?

a) To define a method as a property that can be accessed like an attribute
b) To mark a class as abstract
c) To make an attribute private
d) To override a method in a parent class

Answer:

a) To define a method as a property that can be accessed like an attribute

Explanation:

The @property decorator in Python is used to define a method that can be accessed like an attribute. It allows you to implement getter, setter, and deleter functionality in a clean and intuitive way. This is useful when you want to control access to an attribute, especially when you need to validate the input or compute the attribute’s value dynamically.

class Celsius:
    def __init__(self, temperature=0):
        self._temperature = temperature

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        print("Setting value")
        if value < -273.15:
            raise ValueError("Temperature below -273.15 is not possible")
        self._temperature = value

# Creating an object of Celsius class
c = Celsius(10)
print(c.temperature)  # Output: Getting value
                      #         10
c.temperature = 25    # Output: Setting value

In this example, the temperature property is accessed and modified like an attribute, but the getter and setter methods are automatically invoked. This allows for controlled access to the attribute while keeping the interface simple.

Using the @property decorator helps in creating well-encapsulated classes where the internal state is protected and controlled, but still easily accessible in a user-friendly way.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top