Junior — Middle
Have you had experience using descriptors in Python for managing access to object attributes?
sobes.tech AI
Answer from AI
Yes, descriptors in Python are objects that manage access to attributes of other objects through methods __get__, __set__, and __delete__. They allow controlling reading, writing, and deleting attributes.
An example of using a descriptor for value validation:
class PositiveNumber:
def __get__(self, instance, owner):
return instance._value
def __set__(self, instance, value):
if value < 0:
raise ValueError("Value must be positive")
instance._value = value
class Account:
balance = PositiveNumber()
acc = Account()
acc.balance = 100 # works
acc.balance = -50 # raises ValueError
Thus, descriptors are useful for encapsulating access logic and data validation.