在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ Python 中, __init__ 方法是必然調用的嗎?

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

為什么呢 ?

回答
編輯回答
詆毀你

是必然執(zhí)行的。

2017年5月20日 14:25
編輯回答
萌二代

是的,哪怕 __new__返回了已生成的對象,但是__init__還是必然會執(zhí)行的;
相關代碼如下(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...

2018年6月15日 06:25