在 python 2.7 中扩展类,super() 的用法

lol*_*ter 4 python inheritance python-2.7

也许这是一个愚蠢的问题,但为什么这段代码在 python 2.7 中不起作用?

from ConfigParser import ConfigParser

class MyParser(ConfigParser):
    def __init__(self, cpath):
        super(MyParser, self).__init__()
        self.configpath = cpath
        self.read(self.configpath)
Run Code Online (Sandbox Code Playgroud)

它失败于:

TypeError: must be type, not classobj
Run Code Online (Sandbox Code Playgroud)

在线上super()

Pau*_* Bu 5

很可能因为ConfigParser不继承自object,因此,不是新式。这就是为什么super在那里不起作用的原因。

检查ConfigParser定义并验证它是否是这样的:

class ConfigParser(object): # or inherit from some class who inherit from object
Run Code Online (Sandbox Code Playgroud)

如果不是,那就是问题所在。

我对你的代码的建议是不要使用super. 只需直接调用 self 即可,如下所示ConfigParser

class MyParser(ConfigParser):
    def __init__(self, cpath):
        ConfigParser.__init__(self)
        self.configpath = cpath
        self.read(self.configpath)
Run Code Online (Sandbox Code Playgroud)

  • 如果您查看“ConfigParser.py”(2.7.4)的源代码,“ConfigParser”继承自“RawConfigParser”,这是一个旧式类(不继承自“object”)。 (2认同)