|
3
|
An example of overloading __setattr__ and __getattr__ in classes. This example maps attribute names to dicitonary members.
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. |
3 comments
Add a comment
Sign in to comment
Download
Copy to clipboard

__getattribute__ hook. There is also the __getattribute__() hook, which is called (if defined) for both exisitng and non-exisitng attributes. If __getattribute__() is called and doesn't raise AttributeError then __getattr__() is not called. If __getattribute__() raises AttributeError then __getattr__ gets another change to save the day.
In the __setattr__ method, this line is never True:
Replacing it with the following makes it better:
Please ignore my previous comment!
(The line is checking for attributes added before self.__initialised is set True)