Skip to content
dreamcode
dreamcode
Map
Descriptors
Lesson 63 of 77
+15 XP on finish
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 instance
  • self.fuel = fuel inside __init__ actually calls Positive.__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.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Give Upper a __get__ and a __set__ that stores strings in capital letters, so the program prints NOVA.

Press Run to check your work.