It would be tempting but incorrect to call this the constructor of the class. It's tempting, because it looks like a constructor (by convention,
__init__
is the first method defined for the class), acts like one (it's the first piece of code executed in a newly created instance of the class), and even sounds like one (“init” certainly suggests a constructor-ish nature). Incorrect, because the object has already been constructed by the time__init__
is called, and you already have a valid reference to the new instance of the class.
引用建议将 __init__
作为 构造函数 调用是不正确的,因为在调用 __init__
时对象已经被构造。但!我一直认为 constructor 仅在构造对象后才被调用,因为它本质上是用于初始化实例的数据成员,如果对象不这样做就没有意义constructor 被调用时是否存在? (来自 C++/Java 背景)
最佳答案
如果你有一个类 Foo
那么:
Foo()
是 构造函数Foo.__init__()
是 初始化器-
Foo.__new__()
是分配器
Python 对象的构造只是分配一个新实例,然后初始化该实例。
关于python - __init__ 作为构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578487/