Website Explanation:
object.
__getattr__
(Self, name)
Called when an attribute lookup had not found the attribute in the usual places (i.e. it's not a instance attribute nor Is it found in the class tree forself
).name
is the attribute name.This method should return the(computed) attribute valueorRaise anAttributeError
Exception.
When we want to call something in class, and the class does not, the interpreter is bound to error, stop running, then someone thought: really trouble, every time to re-execute again, if I call the wrong content, the program can put me this error when the default program execution, and do not stop my program to run just fine. So, in order to solve this kind of problem, came out __getattr__ this function.
I guess, because the difficulty of solving the program is also a requirement.
See the error call without __getattr:
#!/usr/bin/python
#-*-Coding:utf-8-*-
Class Student (object):
def __init__ (self):
Self.name = ' Michael '
s = Student ()
Print S.name
Print S.score #Class中没有这个属性
Look, the first print executes normally, and the second one does not have this attribute in class, so it is an error.
Look again, the class with __getattr__:
#!/usr/bin/python
#-*-Coding:utf-8-*-
Class Student (object):
def __init__ (self):
Self.name = ' Michael '
def __getattr__ (self, Other):
If other== ' score ':
Return 99
s = Student ()
Print S.name
Print S.score #Class中没有这个属性
Print S.gg #Class中没有这个属性
Look again, print's score and GG are not defined in class, but both have outputs. Because the program to find __getattr__, just well defined a character to determine if other== ' score ':, so the output of 99, and GG A word did not mention, the default output is None. is not the feeling after the code program when no longer worry about the program to stop running.
Python Class: Object-oriented advanced programming __getattr__