Descriptors in Python and its Protocol
Explore how descriptors in Python enable customization of attribute access by implementing special methods like __get__, __set__, and __delete__. Understand the descriptor protocol, the difference between data and non-data descriptors, and how they influence attribute lookup, empowering advanced object behavior.
We'll cover the following...
Overview of descriptors
Descriptors were introduced in Python way back in version 2.2. They provide the developer ability to add managed attributes to objects.
The methods needed to create a descriptor are __get__,
__set__ and __delete__. If we define any of these
methods, then we have created a descriptor.
The idea behind the descriptor is to get, set or delete attributes from our object’s dictionary. When we access a class attribute, this starts the lookup chain. When we access a class attribute, this starts the lookup chain. The looked up value should be an object with one of our descriptor methods defined, then the descriptor method will be invoked.
Descriptors power a lot of the magic of Python’s internals. They ...