Junior — Middle
What alternative methods or data structures would you use to implement getters and setters in Python instead of using the @property decorator?
sobes.tech AI
Answer from AI
In Python, besides using the @property decorator to create getters and setters, you can implement them using traditional methods or directly use the property() function.
- Traditional get/set methods:
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
def set_name(self, value):
self._name = value
p = Person("Alice")
print(p.get_name())
p.set_name("Bob")
- Using the
property()function:
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
def set_name(self, value):
self._name = value
name = property(get_name, set_name)
p = Person("Alice")
print(p.name) # calls get_name
p.name = "Bob" # calls set_name
Thus, property() allows creating properties without using decorators, while traditional methods provide an explicit interface for attribute access.