Sobes.tech
Junior — Middle

What mechanisms are implemented inside the @property decorator in Python for access control?

sobes.tech AI

Answer from AI

The @property decorator in Python implements a mechanism for managing access to attributes through methods, allowing them to be accessed as regular properties.

Inside @property, a descriptor object is created, which implements the following methods:

  • __get__ — called when reading the property, returns the value via the getter.
  • __set__ — called when assigning a value, if a setter is defined.
  • __delete__ — called when deleting the property, if a deleter is defined.

This allows encapsulating the logic for getting and setting values, for example, for validation or on-the-fly computation.

Example:

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

p = Person("Ivan")
print(p.name)  # calls __get__
p.name = "Peter"  # calls __set__