An example of overloading __setattr__ and __getattr__ in classes. This example maps attribute names to dicitonary members.
Python, 42 lines
Overloading __setattr__ and __getattr__ in classes can be a useful way of custmizing attribute access. For example transforming attributes or function arguments as they are called and set.
__getattr__ and __setattr__ don't behave symetrically and you have to take slight care in their use. For example overloading __setattr__ can make it difficult to set normal attributes in the __init__ method of an object.
This example is a subclass of dict - but maps attribtues to dictionary members. It allows you to set normal attributes in the __init__ method. After that setting attributes creates a new dictionary memebr (rather than an attribute).
Fetching an attribute first checks for normal attribtues, if the attribute asked for isn't present it checks for dictionary members.