Junior — Middle
Can you explain what a property in Python is and how it can be used?
sobes.tech AI
Answer from AI
In Python, property is a built-in decorator that allows you to manage access to class attributes, turning methods into properties. This is convenient for encapsulation: you can define a getter, setter, and deleter for an attribute, while using the syntax as if accessing a regular field.
Example usage:
class Person:
def __init__(self, name):
self._name = name # private attribute
@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 getter
p.name = "Bob" # calls the setter
Thus, property allows controlling reading and writing of attributes, adding validation or computing values on the fly, while maintaining a convenient and understandable interface.