The question I'm about to ask seems to be a duplicate of Python's use of __new__ and __init__?, but regardless, it's still unclear to me exactly what the practical difference between __new__
and __init__
is.
在你急于告诉我__new__
是用来创建对象,__init__
是初始化对象之前,让我明确地说:I get that.,事实上,这个区别对我来说是很自然的,因为我有C++的经验,我们有placement new个,这同样地将对象分配与初始化分开.
Python C API tutorial人解释如下:
新成员负责
所以,是的,我知道__new__
是做什么的,但尽管如此,我不明白为什么它在Python中有用.给出的示例表明,如果您希望"确保实例变量的初始值",那么__new__
可能很有用.__init__
不就是这么做的吗?
在C API教程中,显示了一个示例,其中创建了一个新类型(称为"Noddy"),并定义了该类型的__new__
函数.Noddy类型包含一个名为first
的字符串成员,该字符串成员初始化为空字符串,如下所示:
static PyObject * Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
.....
self->first = PyString_FromString("");
if (self->first == NULL)
{
Py_DECREF(self);
return NULL;
}
.....
}
请注意,如果没有这里定义的__new__
方法,我们必须使用PyType_GenericNew
,它只是将所有实例变量成员初始化为NULL.所以__new__
方法的唯一好处是实例变量将以空字符串开始,而不是NULL.But why is this ever useful, since if we cared about making sure our instance variables are initialized to some default value, we could have just done that in the 103 method?