为了账号安全,请及时绑定邮箱和手机立即绑定

对于新样式的类,super()引发“ TypeError:必须是类型,而不是classobj”

对于新样式的类,super()引发“ TypeError:必须是类型,而不是classobj”

catspeake 2019-10-23 16:09:57
以下用法super()引发TypeError:为什么?>>> from  HTMLParser import HTMLParser>>> class TextParser(HTMLParser):...     def __init__(self):...         super(TextParser, self).__init__()...         self.all_data = []...         >>> TextParser()(...)TypeError: must be type, not classobj在StackOverflow上有一个类似的问题:Python super()引发TypeError,该错误由用户类不是新型类的事实来解释。但是,上面的类是一种新式的类,因为它继承自object:>>> isinstance(HTMLParser(), object)True我想念什么?我如何super()在这里使用?使用HTMLParser.__init__(self)代替super(TextParser, self).__init__()可以工作,但是我想了解TypeError。PS:Joachim指出,成为一个新类实例并不等同于成为一个实例object。我读了很多相反的书,因此感到困惑(基于object实例测试的新型类实例测试的示例:https : //stackoverflow.com/revisions/2655651/3)。
查看完整描述

3 回答

?
慕斯709654

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 = []


查看完整回答
反对 回复 2019-10-23
?
郎朗坤

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


查看完整回答
反对 回复 2019-10-23
  • 3 回答
  • 0 关注
  • 312 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信