基于Python 2.7.9 Docmentation中__call__的说明
Emulating callable objects
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, ...).
翻译如下:
模拟可调用对象
object.__call__(self[, args...])
当实例以函数的形式被调用,如果这个方法被定义了,x(args, args2, ...)是x.__call__(arg1, arg2, ...)的简写形式。
简单来说:如果一个对象x提供了该方法,就可以像函数一样使用它,也就是说x(arg1, arg2...) 等同于调用x.__call__(self, arg1, arg2,...)
基本使用,代码如下:
class Foo(object):
def __call__(self, name):
print('hello, %s' % name)
obj = Foo()
obj('Robert')
# 输出 hello, Robert