python - 什么方法在 Python 类中调用 `__init__()`

标签 python class methods

我想知道如何调用 __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/

相关文章:

python - 在两条评论之间不写入我的文件

python - Python 中的规范 URL 比较?

c++ - 这种赋值方式叫什么?我的变量(值);

ruby - Ruby MetaProgramming 中的一个令人困惑的案例

python - 包含sklearn时如何使用py2exe?

c++ - 为什么前向声明不适用于类?

Java 方法 boolean 值在应该为 true 时返回 false

C++从已实现的虚拟类调用非虚拟方法

python - 如何在 Python 中访问全局变量?

python - 图像数据处理后超出0-1范围