Junior — Middle
Have you used the method of describing and configuring object properties via setters in your projects?
sobes.tech AI
Answer from AI
Yes, in Python, properties with setters (and getters) are often used to control access to object attributes. This allows adding additional logic during assignment, such as validation or updating related data.
Example of using a property with a setter:
class Person:
def __init__(self, age):
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
p = Person(25)
p.age = 30 # valid
# p.age = -5 # raises error
This approach helps encapsulate logic and protect internal object data.