Junior — Middle
Have you dealt with the use of descriptors in your projects?
sobes.tech AI
Answer from AI
In Python, descriptors are objects that manage access to attributes of other objects through the methods __get__, __set__, and __delete__. They are often used to implement properties, data validation, or lazy evaluation.
Example of a simple descriptor for controlling access to an attribute:
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 MyClass:
number = PositiveNumber()
obj = MyClass()
obj.number = 10 # works
obj.number = -5 # raises ValueError
Using descriptors helps centralize the logic for attribute access and validation.