初始化程序与构造函数 [英] Initializer vs Constructor
问题描述
我听说python中的 __ init __
函数不是构造函数,它是一个初始化程序,实际上是 __ new __
函数是构造函数,不同之处在于在创建对象之后调用 __ init __
函数,并调用 __ new __
之前。我对吗?您能否更好地解释这些区别?为什么我们同时需要 __ new __
和 __ init __
?
I have heard that the __init__
function in python is not a Constructor, It's an Initializer and actually the __new__
function is the Constructor and the difference is that the __init__
function is called after the creation of the object and the __new__
called before. Am I right? Can you explain the difference better and why do we need both __new__
and __init__
?
推荐答案
从本质上讲, __ new __
负责创建实例(因此,准确地说<如您所指出的,它是构造函数),而 __ init __
确实是初始化实例状态的一种方式。例如,考虑以下情况:
In essence, __new__
is responsible for creating the instance (thus, it may be accurate to say that it is the constructor, as you've noted) while __init__
is indeed a way of initializing state in an instance. For example, consider this:
class A(object):
def __new__(cls):
return object.__new__(cls)
def __init__(self):
self.instance_method()
def instance_method(self):
print 'success!'
newA = A()
注意 __ init __
接收到参数 self
,而 __ new __
接收到类( cls
)。由于 self
是对该实例的引用,因此很显然,这应该告诉您该实例已在 __ init __
被调用,因为它已通过实例。也可以正是因为实例已经创建而调用实例方法。
Notice that __init__
receives the argument self
, while __new__
receives the class (cls
). Since self
is a reference to the instance, this should tell you quite evidently that the instance is already created by the time __init__
gets called, since it gets passed the instance. It's also possible to call instance methods precisely because the instance has already been created.
关于第二个问题,根据我的经验,很少需要使用 __ new __
。可以肯定的是,在某些情况下,更高级的技术可能会使用 __ new __
,但是这种情况很少见。一个可能使人们倾向于使用 __ new __
的臭名昭著的例子是创建Singleton类(但这不是一个好方法,不是重点)。
As to your second question, there is rarely a need in my experience to use __new__
. To be sure, there are situations where more advanced techniques might make use of __new__
, but those are rare. One notorious example where people might be tempted to use __new__
is in the creation of the Singleton class (whether that's a good technique or not, however, isn't the point).
无论好坏,您基本上都可以控制实例化的过程,以及在您的特定情况下可能意味着什么。
For better or worse, you basically get to control the process of instantiation, and whatever that might mean in your specific situation.
这篇关于初始化程序与构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!