python的__call__

有关python的__call__在官方文档上有这么一句解释 (http://docs.python.org/reference/datamodel.html?highlight=__call__#object.__call__)

object.__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, ...).

当把一个实例当作方法来调用的时候,形如instance(arg1,args2,...),那么实际上调用的就是 instance.__call__(arg1,arg2,...)

先来一个直观的:

In [5]: class A:
   ...:     def __init__(self):
   ...:         print "__init__ method"
   ...:     def __call__(self):
   ...:         print "__call__ method"
   ...:

In [6]: a = A()
__init__ method

In [7]: a()
__call__ method

  

下面的这个可以忽略了。。。。。。

#coding:utf-8
"""
   Demo for __call__
   http://docs.python.org/reference/datamodel.html?  highlight=__call__#object.__call__
   当我们把一个类的实例当作方法来使用的时候,就会调用__call__方法
"""
class A:
    def __init__(self, arg):
        print "init"
        self.arg = arg
        
    def __call__(self):
        print "a"
        print self.arg
        
if __name__ =="__main__":
    c = A("aaaaa")
    c()#这个时候c仅仅是一个实例(instance),我们一般都是c.methodname(), 而现在在实例后面直接添加了(),就是把它当作一个方法来调用,这个时候就会调用c(arg1,arg2,....)就等价于 c.__call__(self,arg1,arg2,...)
    

  

 

posted @ 2012-03-27 09:19  john2000  阅读(1128)  评论(0编辑  收藏  举报