2013-08-25 34 views
0

我有這樣的:混亂使用超與新式類

#! /usr/bin/env python 

class myclass1(object): 

     def __new__(cls,arg): 
       print cls, arg, "in new" 
       ss = super(object,cls) 
       print ss, type(ss) 
       ss.__new__(cls,arg) 
#    super(object,cls).__new__(cls,arg) 
#    return object.__new__(cls,arg) 


     def __init__(self,arg): 
       self.arg = arg + 1 
       print self, self.arg, "in init" 




if __name__ == '__main__': 

     m = myclass1(56) 

它給出了一個錯誤:

$ ./newtest.py 
<class '__main__.myclass1'> 56 in new 
<super: <class 'object'>, <myclass1 object>> <type 'super'> 
Traceback (most recent call last): 
    File "./newtest.py", line 23, in <module> 
    m = myclass1(56) 
    File "./newtest.py", line 9, in __new__ 
    ss.__new__(cls,arg) 
TypeError: super.__new__(myclass1): myclass1 is not a subtype of super 

的錯誤是有效的。我明白了。不過,我現在對於__new__在這個頁面上說的文檔感到困惑:http://docs.python.org/2.6/reference/datamodel.html#object.__new__

問題:根據上面的文檔,我做了什麼錯誤。我對文件理解的差距在哪裏?

回答

1

您基本上需要用object替換爲myclass1ss = super(object,cls)object沒有超類。 myclass1呢。您還需要從ss.__new__(cls,args)中刪除args,因爲object.__new__只有一個參數cls。最終的代碼應該是:

 def __new__(cls,arg): 
       print cls, arg, "in new" 
       ss = super(myclass1,cls) 
       print ss, type(ss) 
       ss.__new__(cls) 
#    super(object,cls).__new__(cls,arg) 
#    return object.__new__(cls,arg) 

在你的文檔的理解的差距,要super第一個參數是你想獲得其超類。不是超類本身。如果你已經知道超類或想硬編碼爲一個固定的,你很可能已經取代ssobject和書面:

 def __new__(cls,arg): 
       print cls, arg, "in new" 
#    ss = super(myclass1,cls) 
       print object, type(object) 
       object.__new__(cls) 
#    super(object,cls).__new__(cls,arg) 
#    return object.__new__(cls,arg) 
+0

我不認爲這就是正確的。如果你看看'super'的幫助,你會看到'super(type,type2) - >綁定超級對象;需要issubclass(type2,type)'。那麼是不是我使用正確的超級電話? – abc

+0

從超級文檔:如果第二個參數被省略,返回的超級對象是未綁定的。如果第二個參數是一個對象,則isinstance(obj,type)必須爲true。如果第二個參數是一個類型,那麼issubclass(type2,type)必須爲真(這對於類方法很有用)。 http://docs.python.org/2/library/functions.html#super – abc

+0

從文檔(爲簡單起見,省略「或兄弟」):「super(type [,object-or-type]) - 返回將方法調用委託給父類的代理對象「。在這裏,單詞'type'指的是參數,而不是父類的類型。試圖解釋它,我意識到這些文檔非常模糊。如果他們已經調用參數'a',則會更清楚。 –

1

超級通常不是在__new__因爲__new__使用是一個靜態方法。此時該對象甚至還不存在,所以沒有超級用戶可以調用。

參考release notes具體方法重寫__new__