Junior — Middle
Have you ever created custom descriptors for objects or classes?
sobes.tech AI
Answer from AI
Yes, I have experience creating custom descriptors in Python. Descriptors are objects that manage access to attributes of other objects through the __get__, __set__, and __delete__ methods.
Here's an example of a simple descriptor that validates that the assigned value is a positive number:
class PositiveNumber:
def __init__(self):
self._value = 0
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
if value <= 0:
raise ValueError("Value must be positive")
self._value = value
class Product:
price = PositiveNumber()
p = Product()
p.price = 100 # works
# p.price = -10 # will raise ValueError
This approach allows centralized control over attribute access and validation.