[zz]__call__()、__getattr__()
http://blog.csdn.net/navygong/archive/2009/08/20/4467471.aspx
1. __call__、__getattr__
1 class B():
2 def __call__(self, name):
3 return getattr(self, name)
4
5 def a(self, text):
6 print 'a' + text
7
8 def b(self, text):
9 print 'b' + text
10
11 class A():
12 def __getattr__(self, name):
13 bb = B()
14 return bb(name)
15
16 aa = A()
17 aa.a('aaaa')
18 aa.b('bbbb')
运行结果:
aaaaa
bbbbb
解释:
16行生成A的一个对象aa,17行来调用aa的方法a,由于A中没有定义方法a(依实例属性->类属性->__getattribute__()->__getattr__()的顺序查找),所以调用A的方法__getattr__得到bb(a),由于bb是类B的一个实例,所以调用bb.__call__(a)得到bb.a,加上传递过来的参数'aaaa',即调用bb.a('aaaa')得到aaaaa。
附上两个函数的解释:
__getattr__( self, name):
Called when an attribute lookup has not found the attribute in the usual places.
__call__( self[, args...])
Called when the instance is "called" as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).
现在应该很容易理解下面的这段程序为什么得到的结果是6 8了吧~~~
1 class Prod:
2 def __init__(self, value):
3 self.value = value
4
5 def __call__(self, other):
6 return self.value * other
7
8 x = Prod(2)
9 print x(3)
10 print x(4)