刷面试题看到的,没看懂这个方法有什么实际用途,官方文档如下:
3.3.6. 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 forx.__call__(arg1, arg2, ...)
.
主要实现的是将类的对象当作函数直接调用
例如:
class Demo(object): def __init__(self, a, b): self.a = a self.b = b def my_print(self,): print("a = ", self.a, "b = ", self.b) def __call__(self, *args, **kwargs): self.a = args[0] self.b = args[1] print("call: a = ", self.a, "b = ", self.b) if __name__ == "__main__": demo = Demo(10, 20) demo.my_print() demo(50, 60)
结果如下:
a = 10 b = 20
call: a = 50 b = 60
需要注意的是:只有当在类中定义了 def __call__() 方法后,才可以实现这个功能,否则会出现语法错误,就是文档中解释的 if this method is defined 的意思。