3 回答

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

TA貢獻1921條經驗 獲得超9個贊
問題是super需要object一個祖先:
>>> 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
經過仔細檢查,發現:
>>> type(myclass)
classobj
但:
>>> class newstyle(object): pass
>>> type(newstyle)
type
因此,解決問題的方法是從對象以及HTMLParser繼承。但是確保對象在MRO類中排在最后:
>>> class myclass(oldstyle, object):
... def __init__(self): super(myclass, self).__init__()
>>> myclass().os
True
添加回答
舉報