Python 中, __init__ 方法是必然调用的吗?

像下面的代码:

class Test(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance:
            return cls.__instance
        else:
            return object.__new__(cls)

    def __init__(self, value):
        self.value = value
        print('__init__')
        Singletone.__instance = self

sl = Test(100)
sl2 = Test(300)

print(sl.value)
print(sl2.value)

我猜测的输出是:

__init__
100
100

然而实际输出是:

__init__
__init__
300
300

为什么呢 ?

阅读 3.6k
2 个回答

是的,哪怕 __new__返回了已生成的对象,但是__init__还是必然会执行的;
相关代码如下(python2.7)

static PyObject *
type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *obj;

    if (type->tp_new == NULL) {
        PyErr_Format(PyExc_TypeError,
                     "cannot create '%.100s' instances",
                     type->tp_name);
        return NULL;
    }
    // new 新建对象
    obj = type->tp_new(type, args, kwds);
    if (obj != NULL) {
        /* Ugly exception: when the call was type(something),
           don't call tp_init on the result. */
        if (type == &PyType_Type &&
            PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
            (kwds == NULL ||
             (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
            return obj;
        /* If the returned object is not an instance of type,
           it won't be initialized. */
        if (!PyType_IsSubtype(obj->ob_type, type))
            return obj;
        type = obj->ob_type;
        if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
            type->tp_init != NULL &&
            // 初始化实例
            type->tp_init(obj, args, kwds) < 0) {
            Py_DECREF(obj);
            obj = NULL;
        }
    }
    return obj;
}

也可以简单看看这篇文章:
https://www.jianshu.com/p/f63...

新手上路,请多包涵

是必然执行的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题