A First Look at Descriptors
Get an introduction to descriptors in Python.
We'll cover the following
Descriptors are another distinctive feature of Python that take object-oriented programming to another level, and their potential allows users to build more powerful and reusable abstractions. Most of the time, the full potential of descriptors is observed in libraries or frameworks.
First, we will explore the main idea behind descriptors to understand their mechanics and internal workings. Once this is clear, it will be easier to assimilate how the different types of descriptors work, which we will explore later.
The machinery behind descriptors
The way descriptors work is not all that complicated, but the problem with them is that there are a lot of caveats to take into consideration, so the implementation details are of the utmost importance here.
To implement descriptors, we need at least two classes. For this generic example, the client
class will take advantage of the functionality we want to implement in the descriptor
(this is generally just a domain model class, a regular abstraction we create for our solution), and the descriptor
class will implement the logic of the descriptor itself.
A descriptor is, therefore, just an object that is an instance of a class that implements the descriptor protocol. This means that the interface of this class must contain at least one of the following magic methods (part of the descriptor protocol as of Python 3.6+):
__get__
__set__
__delete__
__set_name__
For the purposes of this initial high-level introduction, the following naming conventions will be used:
Get hands-on with 1200+ tech skills courses.