__getattr__函数的作用: 假如特点查找(attribute lookup)在实例以及对应的类中(经过__dict__)失败, 那么会调用到类的__getattr__函数;
假如没有定义这个函数,那么抛出AttributeError异常。由此可见,__getattr__一定是作用于特点查找的最后一步
举个栗子:
class A(object):
def __init__(self, a, b):
self.a1 = a
self.b1 = b
print('init')
def mydefault(self, *args):
print('default:' + str(args[0]))
def __getattr__(self, name):
print("other fn:", name)
return self.mydefault
a1 = A(10, 20)
a1.fn1(33)
a1.fn2('hello')
运转结果:
init
other fn: fn1
default:33
other fn: fn2
default:hello
第16行调用fn1特点时,查找不到次特点,程序调用__getattr__办法
用__getattr__办法能够处理调用特点异常
class Student(object):
def __getattr__(self, attrname):
if attrname == "age":
return 'age:40'
else:
raise AttributeError(attrname)
x = Student()
print(x.age) # 40
print(x.name)
这儿定义一个Student类和实例x,并没有特点age,当执行x.age,就调用_getattr_办法动态创建一个特点,执行x.name时,__getattr__办法没有对其处理,抛出异常
age:40
File "XXXX.py", line 10, in <module>
print(x.name)
File "XXXX.py", line 6, in __getattr__
raise AttributeError(attrname)
AttributeError: name
下面展现一个_getattr_经典应用的例子,能够调用dict的键值对
class ObjectDict(dict):
def __init__(self, *args, **kwargs):
super(ObjectDict, self).__init__(*args, **kwargs)
def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = ObjectDict(value)
return value
if __name__ == '__main__':
od = ObjectDict(asf = {'a': 1}, d = True)
print(od.asf, od.asf.a) # {'a': 1} 1
print(od.d) # True