在python 2.7中扩展类,使用super()
发布时间:2020-12-20 11:30:33 所属栏目:Python 来源:网络整理
导读:也许这是一个愚蠢的问题,但为什么这个代码在 python 2.7中不起作用? from ConfigParser import ConfigParserclass MyParser(ConfigParser): def __init__(self,cpath): super(MyParser,self).__init__() self.configpath = cpath self.read(self.configpath
也许这是一个愚蠢的问题,但为什么这个代码在
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()行. 解决方法
很可能是因为ConfigParser不从对象继承,因此,不是
new-style class.这就是为什么超级不能在那里工作的原因.
检查ConfigParser定义并验证它是否是这样的: class ConfigParser(object): # or inherit from some class who inherit from object 如果没有,那就是问题所在. 我对你的代码的建议不是使用super.只需在ConfigParser上直接调用self,就像这样: class MyParser(ConfigParser): def __init__(self,cpath): ConfigParser.__init__(self) self.configpath = cpath self.read(self.configpath) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |