__call__ 在 class 中调用方法时

__call__ when calling a method inside the class

我正在尝试理解 __call__ (python3) 的含义。写这个是为了区分每个方法 __init____call__ 和测试方法。

#!/usr/bin/python3

class thara(object):

   def __init__(self):
        print("init called")

   def __call__(self):
       print("call called")

   def test(self):
       print("test called")

x=thara()  ### constructor calling here
x()   ## __call__  calling here
x.test() ## test method calling here

我的问题是当我启动 x.test() 时,为什么它不调用 __call__?我在想的是,如果我启动 x.test() 将启动实例 x(),它应该根据我的输出 [=] 调用 __call__ 方法 automatically.But 13=] 只会在启动时调用 x().

谁能解释一下。

https://docs.python.org/2/reference/datamodel.html#object.__call__

__call__ 当像函数一样调用实例时调用。这就是您对 x() 所做的。 x.test()是调用实例的方法,不是实例本身。