刷面試題看到的,沒看懂這個方法有什么實際用途,官方文檔如下:
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 的意思。