__init__ 作为构造函数? [英] __init__ as a constructor?
问题描述
这很诱人但不正确称其为构造函数班级.很诱人,因为它看起来就像一个构造函数(按照惯例,__init__
是为类定义的第一个方法),就像一个(它是在 a 中执行的第一段代码新创建的类实例),甚至听起来像一个(init"当然建议一个构造函数自然).不正确,因为对象已经由时间 __init__
被调用,你已经有一个有效的参考类的新实例.
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 只在对象被构造后才被调用,因为它本质上是用来初始化实例的数据成员的,如果对象没有构造函数被调用时存在吗?(来自 C++/Java 背景)
Quote suggests it is incorrect to call __init__
as a constructor because the object is already constructed by the time __init__
is called. But! I have always been under the impression that the constructor is called only after the object is constructed because it is essentially used to initialized the data members of the instance which wouldn't make sense if the object didn't exist by the time constructor was called? (coming from C++/Java background)
推荐答案
如果你有一个类 Foo
那么:
If you have a class Foo
then:
Foo()
是构造函数Foo.__init__()
是初始化器Foo.__new__()
是分配器
Python 对象的构造只是分配一个新实例,然后初始化该实例.
Construction of a Python object is simply allocation of a new instance followed by initialization of said instance.
这篇关于__init__ 作为构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!