Any object with a
__get__() method, and optionally
methods, accepting specific parameters is said to follow the
descriptor protocol. Such an object qualifies as
a descriptor and can be placed inside a class's
__dict__ to do something special when an attribute
is retrieved, set or deleted. An empty descriptor is shown below.
Example 1.3. A simple descriptor
Called when attribute is read (eg.
Called when attribute is set on an instance
Called when attribute is deleted from an instance
What we defined above is a class that can be instantiated to create a descriptor. Let's see how we can create a descriptor, attach it to a class and put it to work.
Example 1.4. Using a descriptor
Now the attribute called
Sticking a value
directly in the instance's
is futile. This still calls
anything. This replaces the descriptor with a new string object. After
Note that when accessed from the class itself, only the
__get__() method comes in the picture, setting or
deleting the attribute will actually replace or remove the
Descriptors work only when attached to classes. Sticking a descriptor in an object that is not a class gives us nothing.