有關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__ methodIn [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,...)