__getattribute__, __getattr__用法

 1 class AttriubteTest(object):
 2     def __init__(self):
 3         self.a = 0.01
 4         self.b = 1.22
 5 
 6     def __getattribute__(self, item):
 7         if item == 'a':
 8             return self.a #抛RuntimeError: maximum recursion depth exceeded in cmp异常
 9         else:
10             return object.__getattribute__(self, item)
11 
12     def __getattr__(self, item):
13         print '找不到属性,怎么办?可以设置一个默认值?'
14         return 0.00
15 if __name__ == '__main__':
16     d = AttriubteTest()
17     #print d.a 
18     print d.b #能正确返回值
19     print d.bb #当无属性时自动调用__getattr__方法

 

posted @ 2013-01-15 10:35  践道者  阅读(362)  评论(0编辑  收藏  举报