【问题标题】:Python call super constructor [duplicate]Python调用超级构造函数[重复]
【发布时间】:2015-11-30 13:40:27
【问题描述】:

我正在使用模块 HTMLParser 并想要创建一个子类。但是我无法调用超级构造函数,我做错了什么?

class CustomParser(HTMLParser):

def __init__(self):
    super(CustomParser, self).__init__()

堆栈跟踪:

Traceback (most recent call last):
File "C:\Users\Marc\Phyton\rafafafaf\src\test.py", line 20, in <module>
C = CustomParser()
File "C:\Users\Marc\Phyton\rafafafaf\src\test.py", line 17, in __init__
super(CustomParser, self).__init__()
TypeError: must be type, not classobj

【问题讨论】:

    标签: python constructor super


    【解决方案1】:

    正如错误消息所说,HTMLParser 是一个老式类(类型“classobj”),因此不支持协作式super() 调用。从子类调用父类方法的正确方法是直接类访问,即:

    class CustomParser(HTMLParser):
        def __init__(self):
            HTMLParser.__init__(self)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      class CustomParser(HTMLParser):
          def __init__(self):
              HTMLParser.__init__(self)
      

      或者这个:

      class CustomParser(HTMLParser, object):
          def __init__(self):
              super(CustomParser, self).__init__(self)
      

      详情: https://stackoverflow.com/a/9719731/320104

      【讨论】:

      • 已编辑,请验证
      猜你喜欢
      • 2020-10-14
      • 1970-01-01
      • 2011-01-24
      • 2021-11-23
      • 1970-01-01
      • 2016-07-16
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多