Descriptors - The Magic behind python - Raymond Hettinger¶
What is a descriptor¶
It is like a magic dot…
Reading the dot, invokes its magic.
http://tinyurl.com/d63d has all the gory details.
An object that defines
Must be put into the class dictionary, not in the instance dictionary. If you put it in the instance dictionary, it will not be invoked. It is only invoked when it is put into the class dictionary.
__get__is invoked when you read the
__set__when something is assigned to the object.
__del__when the object is deleted?
Property is a descriptor.
It is trivially easy to write your own variants.
The following two
__getattribute__ methods are not the same:
A.x translates to
a.x translates to
If we override
__getattribute__ you can create your own new types
of magic for dotted access.
Every time you see a
Super provides it’s own
__getattribute__. It’s special trick is
to search the
__mro__ during dotted access.
Functions are descriptors, running
dir(f) shows that functions have
If you put a method in a class dictionary, the
__get__ method will
activate upon dotted access.
How python works¶
Dotted attribute access like
a.x calls the