Editor

Predict the Attribute Access

Advanced · Predict the output · from __getattr__ and __setattr__: Dynamic Attribute Access in Python

From the lesson: __getattr__ and __setattr__: Dynamic Attribute Access in Python

Most of the time, Python attributes are straightforward. You set obj.x = 5, and later obj.x gives you 5. But what if you want attributes that don't actually exist - attributes that are computed on the fly, or that trigger side effects when accessed?

Read the lesson

What does the following code print?

class Magic:
    x = 10
    
    def __getattr__(self, name):
        return f'fallback:{name}'

obj = Magic()
obj.y = 20
print(obj.x)
print(obj.y)
print(obj.z)

Remember: __getattr__ is only called when normal lookup fails.

# Type your predicted output

More __getattr__ and __setattr__ exercises

All Python exercises · 50 practice problems · Metaprogramming quiz