3 回答

TA贡献1911条经验 获得超7个赞
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贡献1848条经验 获得超6个赞
问题是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
添加回答
举报