Course contentsShow
← Python
Lesson 478 of 1,0607. Object-Oriented ProgrammingFree lesson

Applying Descriptor Protocols for Custom Logic

Implement the descriptor protocol to create reusable logic for attribute access that goes beyond simple property decorators.

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

  1. __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.
  2. __set__: Instead of writing a setter method for every field, you write the logic once inside this method. When you do item.price = 10, Python calls PositiveNumber.__set__, which validates the value before storing it in the instance's __dict__.
  3. Encapsulation: You can now reuse PositiveNumber in any class—Product, BankAccount, or Sensor—without repeating the if value < 0 logic.

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.