How do I override the __getattr__ method of a class without breaking the default behavior?
How do I override the __getattr__ method of a class without breaking the default
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Overriding
__getattr__should be fine —__getattr__is only called as a last resort i.e. if there are no attributes in the instance that match the name. For instance, if you accessfoo.bar, then__getattr__will only be called iffoohas no attribute calledbar. If the attribute is one you don’t want to handle, raiseAttributeError:However, unlike
__getattr__,__getattribute__will be called first (only works for new style classes i.e. those that inherit from object). In this case, you can preserve default behaviour like so:See the Python docs for more.