有关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