Q16: What are Python Descriptors and how do __get__ and __set__ operate?

A Descriptor is an object defining attribute access behavior via __get__(), __set__(), or __delete__() methods. Powers @property, @classmethod, @staticmethod, and ORM field mappings.

Custom Validation Descriptor
class BoundedNumber:
    def __init__(self, min_val, max_val):
        self.min_val = min_val
        self.max_val = max_val
        
    def __set_name__(self, owner, name):
        self.name = name
        
    def __set__(self, instance, value):
        if not (self.min_val <= value <= self.max_val):
            raise ValueError(f"{self.name} out of bounds")
        instance.__dict__[self.name] = value
💡 Descriptors intercept attribute writes (__set__) to validate values systematically.
Key Takeaways
  • Enables custom attribute management logic.
  • Powers properties, methods, and ORM fields under the hood.
Knowledge Check

Which built-in Python decorator is implemented as a data descriptor?