In this lesson, you will learn how to encapsulate reusable validation and transformation logic across multiple class attributes using the descriptor protocol.
While @property decorators work well for individual methods, they create boilerplate if you need to apply the same validation (like checking for positive integers) across many fields in different classes. A descriptor is an object that defines how attribute access—getting, setting, or deleting—should behave by implementing one or more of the __get__, __set__, or __delete__ methods.
The Power of Reusability
When you define a class containing __set__, any instance of that class assigned to an attribute in another class becomes a "data descriptor." Python will automatically route access through your custom logic.
Consider a descriptor that ensures a value is always a positive number:
class PositiveNumber:
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if value < 0:
raise ValueError(f"{self.name} must be positive")
instance.__dict__[self.name] = value
class InventoryItem:
price = PositiveNumber()
stock = PositiveNumber()
def __init__(self, price, stock):
self.price = price
self.stock = stock
How It Works
__set_name__: This optional method (introduced in newer Python versions) allows the descriptor to "know" the name of the attribute it is assigned to, helping us construct clear error messages.__set__: Instead of writing a setter method for every field, you write the logic once inside this method. When you doitem.price = 10, Python callsPositiveNumber.__set__, which validates the value before storing it in the instance's__dict__.- Encapsulation: You can now reuse
PositiveNumberin any class—Product,BankAccount, orSensor—without repeating theif value < 0logic.
By moving attribute logic into its own class, you keep your business models clean and your validation rules centralized, making your code significantly easier to maintain and test.
Key Takeaway: Descriptors allow you to move repetitive attribute access logic into a standalone, reusable class, ensuring consistent behavior across your entire object model.