Junior — Middle
Can you explain what the property decorator in Python is and how it is used?
sobes.tech AI
Answer from AI
The @property decorator in Python is used to create class properties that appear as regular attributes but invoke methods when accessed.
This allows encapsulating the logic for getting, setting, and deleting an attribute's value without changing the class interface.
Example of usage:
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("Alice")
print(p.name) # calls the name() method
p.name = "Bob" # calls the setter
Here, name is a property; reading it calls the method decorated with @property, and setting it calls the method with @name.setter. This allows controlling access to the internal attribute _name.