标签:
getattr() 为 函数,而__getattr__(), __getattribute__()为类的方法
1. getattr() 参数为 (object,attr_name,default value)
会调用该object的__getattribute__()方法,如果没有返回值,继续调用__getattr__()方法
2. 任何调用实例的属性值,都会调用到__getattribute__方法,如果没有返回值会继续调用__getattr__(),也就是__getattr__() 相当于exception机制,不一定会被调用
一个demo
1 class demo(object):
2 def __init__(self):
3 self.a = 10
4
5 def __getattribute__(self, item):
6 print "__getattribute__ is called "
7 return super(demo,self).__getattribute__(item)
8
9 def __getattr__(self, item):
10 print "__getattr__ is called"
11 return item
12
13
14 if __name__ == ‘__main__‘:
15 d = demo()
16 print d.a
17 print d.b
18 print getattr(d,‘a‘)
19 print getattr(d,a,0)
python中getattr(),__getattr__(),__getattribute__()探究
标签:
原文地址:http://www.cnblogs.com/pyimt/p/5069931.html