PYTHON EXPERTChapter 11 · Python Expert
Descriptors
A descriptor is an object that controls attribute access on another class. Any class with __get__ (and optionally __set__) placed as a class attribute intercepts reads and writes of that attribute on every instance. Properties, methods and @classmethod are all built on descriptors. __set_name__ tells the descriptor which attribute name it was given.
Worked example
How it reads
fuel = Positive()lives on the class, but guards every instanceself.fuel = fuelinside__init__actually callsPositive.__set__- The real value is stored under a private name like
_fuel

Cloud tip: One descriptor class can guard many attributes. That is what makes it better than writing a property for each one.


