我有這樣的:混亂使用超與新式類
#! /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__
問題:根據上面的文檔,我做了什麼錯誤。我對文件理解的差距在哪裏?
我不認爲這就是正確的。如果你看看'super'的幫助,你會看到'super(type,type2) - >綁定超級對象;需要issubclass(type2,type)'。那麼是不是我使用正確的超級電話? – abc
從超級文檔:如果第二個參數被省略,返回的超級對象是未綁定的。如果第二個參數是一個對象,則isinstance(obj,type)必須爲true。如果第二個參數是一個類型,那麼issubclass(type2,type)必須爲真(這對於類方法很有用)。 http://docs.python.org/2/library/functions.html#super – abc
從文檔(爲簡單起見,省略「或兄弟」):「super(type [,object-or-type]) - 返回將方法調用委託給父類的代理對象「。在這裏,單詞'type'指的是參數,而不是父類的類型。試圖解釋它,我意識到這些文檔非常模糊。如果他們已經調用參數'a',則會更清楚。 –