Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

The @property decorator in Python is used to create class properties that look like attributes but can execute computations or checks when accessed. This allows controlling access to data without changing the class interface.

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

Thus, you can access person.name as an attribute, but behind the scenes, validation or computation logic is executed.