Sobes.tech
Middle

What is a property decorator and what is it used for in Python?

sobes.tech AI

Answer from AI

property is a built-in decorator in Python that allows defining class properties that behave like attributes when accessed but can have their own getter, setter, and deleter methods.

Used for:

  1. Managing access to attributes: Allows validation, data transformation, or other actions when getting or setting an attribute's value.
  2. Creating "computable" attributes: An attribute may not store a value directly but compute it on the fly each time it is accessed.
  3. Smooth transition from public attributes to access methods: You can start with a simple public attribute and then add logic using @property without changing the code that uses this attribute.
  4. Reusing getter/setter logic: For the same property, you can define getter, setter, and deleter. The logic related to these operations is centralized in one place.
class MyClass:
    def __init__(self, value):
        self._value = value  # Private attribute

    @property
    def value(self):  # Getter
        """Returns the value."""
        print("Accessed value")
        return self._value

    @value.setter
    def value(self, new_value):  # Setter
        """Sets a new value."""
        if not isinstance(new_value, (int, float)):
            raise TypeError("Value must be a number")
        print(f"Setting value to {new_value}")
        self._value = new_value

    @value.deleter
    def value(self):  # Deleter
        """Deletes the value."""
        print("Deleting value")
        del self._value

# Example usage
obj = MyClass(10)
print(obj.value)  # Calls getter
obj.value = 20   # Calls setter
print(obj.value)
# del obj.value   # Calls deleter - be careful, may cause errors if attribute is used later

Without @property, you would have to use separate methods get_value(), set_value(), delete_value(), which is less convenient for data access.