我想知道如何调用 __init__()
方法。 __new__()
调用它,还是 __call__()
在使用 __new__()
或其他方式创建实例后调用它?
最佳答案
Python 判断是否__new__()应该调用 __init__():
If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
如果 __new__() 被覆盖并且不返回类的实例,则 不会 调用 __init__()。
__call__()当实例对象像函数一样被调用时被调用:
class MyObj:
def __call__():
print 'Called!'
>>> mo = MyObj()
>>> mo()
Called!
当然,您可以使用您想要的任何参数和逻辑来定义 __call__()。
关于python - 什么方法在 Python 类中调用 `__init__()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7230636/