有關python的call在官方文檔上有這麼一句解釋 (call#object.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,…)
class A:
def __init__(self):
print "__init__ method"
def __call__(self):
print "__call__ method"
a = A()
#__init__ method
a()
#__call__ method
其他特殊函數的功能如下,用代碼說話
class A(object):
def __init__(self, arg):
print "__init__ method", arg
def __call__(self, arg):
print "__call__ method", arg
def __setattr__(self, key, value):
print "__setattr__ method", key, value
def __getattr__(self, key):
print "__getattr__ method", key
def __delattr__(self, key):
print "__delattr__ method", key
a = A('1')
# __init__ method 1
a('2')
# __call__ method 2
a.attr = '3'
# __setattr__ method attr 3
a.attr
# __getattr__ method attr
del a.attr
# __delattr__ method attr