3

也许这是一个愚蠢的问题,但为什么这段代码在 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)

它失败了:

TypeError: must be type, not classobj

super()线。

4

2 回答 2

4

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

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

class ConfigParser(object): # or inherit from some class who inherit from object

如果没有,那就是问题所在。

我对您的代码的建议是不要使用super. 只需像这样直接调用 self ConfigParser

class MyParser(ConfigParser):
    def __init__(self, cpath):
        ConfigParser.__init__(self)
        self.configpath = cpath
        self.read(self.configpath)
于 2013-10-11T16:43:05.807 回答
3

问题是这ConfigParser是一个老式的类。 super不适用于旧式课程。相反,使用显式调用__init__

def __init__(self, cpath):
     ConfigParser.__init__(self)
     self.configpath = cpath
     self.read(self.configpath)

例如,请参阅这个问题,了解新旧样式类的解释。

于 2013-10-11T16:43:28.353 回答