Build a Default Dictionary Object
Advanced · Write the code · 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 lessonCreate a class DefaultObj that returns a default value for any attribute that doesn't exist. The constructor takes the default value.
Regular attributes should work normally. Only missing attributes should return the default.
obj = DefaultObj('N/A')
obj.name = 'Alice'
print(obj.name) # Alice
print(obj.missing) # N/A
print(obj.whatever) # N/Aclass DefaultObj:
# Your code here
pass
obj = DefaultObj('N/A')
obj.name = 'Alice'
print(obj.name)
print(obj.missing)
print(obj.whatever)
More __getattr__ and __setattr__ exercises
- Predict the Attribute AccessAdvanced
- Build a Read-Only ObjectAdvanced
- Fix the Recursive __setattr__Advanced
- Build a Proxy ObjectAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz