3 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
super()僅可用于新型類(lèi),這意味著根類(lèi)需要從'object'類(lèi)繼承。
例如,頂級(jí)類(lèi)需要像這樣:
class SomeClass(object):
def __init__(self):
....
不
class SomeClass():
def __init__(self):
....
因此,解決方案是直接調(diào)用父級(jí)的init方法,如下所示:
class TextParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.all_data = []

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
問(wèn)題是super需要object一個(gè)祖先:
>>> class oldstyle:
... def __init__(self): self.os = True
>>> class myclass(oldstyle):
... def __init__(self): super(myclass, self).__init__()
>>> myclass()
TypeError: must be type, not classobj
經(jīng)過(guò)仔細(xì)檢查,發(fā)現(xiàn):
>>> type(myclass)
classobj
但:
>>> class newstyle(object): pass
>>> type(newstyle)
type
因此,解決問(wèn)題的方法是從對(duì)象以及HTMLParser繼承。但是確保對(duì)象在MRO類(lèi)中排在最后:
>>> class myclass(oldstyle, object):
... def __init__(self): super(myclass, self).__init__()
>>> myclass().os
True
添加回答
舉報(bào)