In this lesson, you will learn how to create custom descriptors to intercept and control how attributes are accessed, set, or deleted in your class instances.
What are Descriptors?
At its core, a descriptor is a class that defines at least one of the following "magic" methods: __get__, __set__, or __delete__. By implementing these, you can take control of attribute access. Instead of a simple variable lookup, Python will route the request through your logic, allowing you to add validation, logging, or dynamic computation.
The Anatomy of a Descriptor
Think of a descriptor as a "smart proxy." When you access an attribute that is an instance of a descriptor, Python calls the descriptor's methods instead of returning the raw value.
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()
item = Product()
item.price = 50 # Success
item.price = -10 # Raises ValueError: Value must be positive!
Why use them?
In the example above, the price attribute isn't just a stored value; it is now guarded by logic. Because price is an instance of PositiveNumber inside the Product class, every time you perform item.price = x, Python invokes PositiveNumber.__set__.
This is incredibly powerful for:
- Data Validation: Enforcing constraints (like types or ranges) at the moment of assignment.
- Computed Attributes: Calculating values on-the-fly (like returning a cached result or performing a conversion) inside
__get__. - Lazy Loading: Loading expensive data from a database only when it is actually accessed.
Descriptors allow you to keep your core business logic clean by moving repetitive "boilerplate" validation or access logic into reusable, standalone objects.
Key Takeaway: Descriptors allow you to replace standard attribute access with custom logic, giving you granular control over the behavior of data within your objects.