Build a Read-Only 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 Frozen that allows attributes to be set in __init__ but raises AttributeError with the message 'Cannot modify frozen object' if anyone tries to set an attribute after initialization.
Use a flag _frozen to track whether initialization is complete.
obj = Frozen(name='Alice', age=30)
print(obj.name) # Alice
print(obj.age) # 30class Frozen:
def __init__(self, **kwargs):
for key, value in kwargs.items():
# Need to set attributes without triggering the freeze
pass
# Mark as frozen
pass
# Test it
obj = Frozen(name='Alice', age=30)
print(obj.name)
print(obj.age)
More __getattr__ and __setattr__ exercises
- Build a Default Dictionary ObjectAdvanced
- Predict the Attribute AccessAdvanced
- Fix the Recursive __setattr__Advanced
- Build a Proxy ObjectAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz