Accessing other instance attributes using __getattr __ (self, name)

The Python documentation in the __getattr__ function says:

Note that if an attribute is found through the normal mechanism, __getattr __ () is not called. (This is a deliberate asymmetry between __getattr __ () and __setattr __ ().) This is done for efficiency reasons as well as otherwise __getattr __ () will not be able to access other instance attributes.

I have a problem understanding the last statement:

does not have access to other instance attributes

How exactly would there be no access to other attributes? (I assume this has something to do with infinite recursion, but are there other ways to access instance attributes, for example, from self.__dict__ directy?)

+7
source share
2 answers

You will have infinite recursion if you try to use self.__dict__[key] , since self.__dict__ will call __getattr__ , etc. etc. Of course, you can exit this loop if you use object.__getattr__(self,key) , but this only works for new style classes. There is no general mechanism that you could use with old style classes.

Note that you do not have this problem with __setattr__ , because in this case, you can directly use self.__dict__ (hence asymmetry).

+3
source

The __getattribute__() magic method is a couple with __setattr__() , but with great power comes a lot of responsibility. __getattr__() provided so that you do not need to take on most of the responsibility. As @mgilson notes in the comments, if __getattr__() worked like __getattribute__() , you would not be able to access any attributes from the instance from __getattr__() , because even for viewing self.__dict__ you need to use attribute search machines.

+1
source

All Articles