Content · Programming · Python

Python Descriptors: __get__, __set__, and __delete__

Use descriptors to customize how attributes are accessed or assigned.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Use descriptors to customize how attributes are accessed or assigned.

How It Works


A descriptor implements __get__, __set__, or __delete__ on an object stored in a class attribute. Properties, methods, and many framework field systems build on descriptor behavior.

Data descriptors implement __set__ or __delete__ and have different lookup priority from nondata descriptors.

Step-by-Step Example


class NonNegative:
    def __set_name__(self, owner_class, attribute_name):
        self.storage_name = "_" + attribute_name

    def __get__(self, instance, owner_class):
        if instance is None:
            return self
        return getattr(instance, self.storage_name)

    def __set__(self, instance, value):
        if value < 0:
            raise ValueError("Value must be nonnegative")
        setattr(instance, self.storage_name, value)

class Stock:
    quantity = NonNegative()

stock = Stock()
stock.quantity = 6
print(stock.quantity)

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The function definition gives the operation a reusable name and makes its inputs explicit.

A successful run of this example prints the following output:

6

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Build a descriptor that accepts only nonempty string names.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Putting shared per-instance values directly on the descriptor instead of the target instance.
  • Triggering recursive descriptor access by assigning to the same managed attribute.

Key Takeaways


  • Use descriptors to customize how attributes are accessed or assigned.
  • A descriptor implements __get__, __set__, or __delete__ on an object stored in a class attribute.
  • Data descriptors implement __set__ or __delete__ and have different lookup priority from nondata descriptors.
Share this resourceSend this page to someone who may find it useful.