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 appear as regular attributes but can have methods behind their reading, writing, or deleting.

This allows controlling access to data, performing additional logic when getting or setting a value, while maintaining a convenient syntax.

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)  # Access via @property
p.name = "Peter"  # Call setter
# p.name = ""  # This will raise ValueError

Thus, @property helps encapsulate access logic to attributes, making the code cleaner and safer.