Python沒有執行__init__

來源:互聯網
上載者:User

標籤:cal   編譯   ima   為什麼   lob   添加   function   代碼   line   

疑惑 提出問題

前天同事問我一個問題,為什麼這個指令碼中的沒有調用A 的__init__。指令碼如下:

 1 class A(object): 2     def __init__(self, *args, **kwargs): 3         print "Call init from %s" %self.__class__ 4  5     def __new__(cls, *args, **kwargs): 6         obj = object.__new__(cls, *args, **kwargs) 7         print "Call new from %s" %obj.__class__ 8         return obj 9 10 11 class B(object):12     def __init__(self, *args, **kwargs):13         print "Call init from %s" %self.__class__14 15     def __new__(cls, *args, **kwargs):16         obj = object.__new__(A, *args, **kwargs)17         print "Call new from %s" %obj.__class__18         return obj19 20 b = B()

其實我也比較奇怪,這個指令碼寫的比較奇怪,class B的的__new__返回了A的執行個體。也只是只執行了B的__new__方法,並沒有執行A的__init__方法。

深入 迷失

遇到這個問題:

要深入首先查看了一下代碼的編譯後的python指令,查看B,是B的__init__方法的指令,

如,為了具體查看B()方法是如何調用,就添加了一個方法test_B。B()顯示僅僅是兩條指令

LOAD_GLOBAL

CALL_FUNCTION

查看Python原始碼,到

PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
{
    ternaryfunc call;

    if ((call = func->ob_type->tp_call) != NULL) {
        PyObject *result;
        if (Py_EnterRecursiveCall(" while calling a Python object"))
            return NULL;
        result = (*call)(func, arg, kw);

**************看到這裡的時候有點迷失了,不知道tp_call是個什麼東西了,不確定由typeobject來操作

(這個必須進行檢討因為tp_call已已經明確了他來自哪裡)***************

調試 問題解決

 

最後使出了,大招對Python原始碼進行調試,在Linux上編譯python原始碼加上參數--with-debug, 然後執行gdb -ex r --args python test.py

在call_function,do_call,PyObject_Call 執行到之後,打上斷點。看到他運行到了

type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    obj = type->tp_new(type, args, kwds);
    if (obj != NULL) {
        if (!PyType_IsSubtype(obj->ob_type, type))
            return obj;

,這個時候我再去看代碼。發現哪裡已經寫好注釋了:

/* If the returned object is not an instance of type,
           it won‘t be initialized. */

好吧,很明確了了。沒有產生和class類型一致的instance,就不會進行初始化。即調用__init__。

問題解決了。。也學習了

要問我怎麼知道在那個地方打斷點,因為我已經看過了代碼,只是理解沒有那麼深。

Python沒有執行__init__

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.