In this lesson, you will learn how to intercept and customize attribute access in your objects by implementing the core descriptor protocol methods: __get__, __set__, and __delete__.
What is a Descriptor?
A descriptor is any object that defines at least one of these three special methods. When you place a descriptor instance as a class attribute of another class, Python gives you "hooks" into whenever that attribute is accessed, modified, or removed.
The Protocol Methods
__get__(self, instance, owner): Triggered when you access the attribute (e.g.,obj.x).__set__(self, instance, value): Triggered when you assign a value (e.g.,obj.x = 10).__delete__(self, instance): Triggered when you delete the attribute (e.g.,del obj.x).
Practical Example
Imagine you want to create a PositiveNumber attribute that raises an error if someone tries to assign a negative 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()
# Usage
p = Product()
p.price = 50 # Calls __set__
print(p.price) # Calls __get__
# p.price = -10 # Raises ValueError
How it works
In the Product class, price is not a simple variable; it is an instance of PositiveNumber. When you execute p.price = 50, Python notices the __set__ method on the descriptor and hands the assignment off to it instead of simply storing the value in p.__dict__.
The instance argument represents the Product object being accessed, while owner refers to the Product class itself. This allows your descriptor to manage state either globally (within the descriptor instance) or specifically per-object by using the instance argument to store data in a dictionary, effectively creating "managed" attributes.
Key Takeaway: The descriptor protocol allows you to inject custom logic into attribute access, enabling powerful features like automatic type validation, logging, or lazy attribute initialization.