我试图理解__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
Run Code Online (Sandbox Code Playgroud)
我的问题是当我启动时x.test(),为什么不调用__call__?我在想的是,如果我启动 x.test() 将启动实例x(),它应该__call__自动调用该 方法。但根据我的输出__call__只会在启动时调用x()。
有人可以解释一下。
https://docs.python.org/2/reference/datamodel.html#object.__call__
__call__ 在实例像函数一样被调用时被调用。这就是您对x(). x.test()正在调用实例的方法,而不是实例本身。