0
0
PythonConceptIntermediate · 3 min read

What is Descriptor in Python: Explanation and Examples

A descriptor in Python is an object attribute with special methods that control how values are accessed, set, or deleted. It lets you customize attribute behavior by defining __get__, __set__, and __delete__ methods.
⚙️

How It Works

Think of a descriptor as a smart gatekeeper for an attribute in a Python class. Instead of just storing a value, it controls what happens when you get, set, or delete that attribute. This is done by defining special methods: __get__ to fetch the value, __set__ to change it, and __delete__ to remove it.

Imagine you have a mailbox with a lock. The descriptor is like the lock mechanism that decides who can open the mailbox and what happens when you try to put mail inside or take it out. This lets you add rules or extra actions whenever the attribute is used.

💻

Example

This example shows a descriptor that manages an attribute called value. It prints messages when the attribute is accessed or changed.

python
class Descriptor:
    def __init__(self):
        self._value = None

    def __get__(self, instance, owner):
        print('Getting value')
        return self._value

    def __set__(self, instance, value):
        print('Setting value to', value)
        self._value = value

    def __delete__(self, instance):
        print('Deleting value')
        self._value = None

class MyClass:
    attr = Descriptor()

obj = MyClass()
obj.attr = 10
print(obj.attr)
del obj.attr
print(obj.attr)
Output
Setting value to 10 Getting value 10 Deleting value Getting value None
🎯

When to Use

Use descriptors when you want to control how attributes behave in your classes beyond simple storage. They are great for adding validation, logging, computed properties, or managing resources.

For example, descriptors are used internally in Python for properties, methods, and static methods. You might use them to ensure a value is always positive, to automatically convert types, or to track changes to an attribute.

Key Points

  • A descriptor is a class that defines __get__, __set__, or __delete__ methods.
  • It controls attribute access and modification in other classes.
  • Descriptors enable reusable and clean attribute management logic.
  • Python’s built-in property is a common example of a descriptor.

Key Takeaways

A descriptor customizes attribute access by defining __get__, __set__, and __delete__ methods.
Descriptors act like smart gatekeepers controlling how attributes behave in classes.
They are useful for validation, logging, computed properties, and resource management.
Python’s property decorator is a built-in example of a descriptor.
Use descriptors to keep attribute logic reusable and clean.