Skip to content
dreamcode
dreamcode
Map
Metaprogramming
Lesson 64 of 77
+15 XP on finish
PYTHON EXPERTChapter 11 · Python Expert

Dynamic properties and descriptors

Python lets you customize attribute access using metaprogramming. Override __getattr__ to intercept missing attributes, __setattr__ for writes, and use property descriptors to manage class variables.

Worked example

How it reads

  • __getattr__(self, name) runs only when the attribute does not exist
  • It returns a computed value dynamically
Cloud tip: Use __getattr__ for fallback lookup; use __getattribute__ to intercept every attribute access (but watch out for infinite recursion).
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Use setattr(c, "level", 3) to add an attribute by name, then print c.level (3) and getattr(c, "mode") (dreamy).

Press Run to check your work.