通过多重继承将旧式类转换为新式类是否安全?

7 投票
1 回答
268 浏览
提问于 2025-04-11 18:53

在我写的一个程序里,我想做一个只读的配置解析器,这样它就可以安全地在全局使用。我之前没意识到,原来 SafeConfigParser 是一个旧式类,所以我需要像这样去继承它:

class ConstParser(SafeConfigParser, object):
     """This is a implementation of the SafeConfigParser that can't
        write any values.  This is to ensure that it can only be filled
        once and won't get messy with multiple modules writing to it."""
    def __init__(self, files, defaults={}):
        super(ConstParser, self).__init__(defaults)
        self.read(files)
    def set(self, *args, **argd):
        raise NotImplementedError()
    def write(self, *args, **argd):
        raise NotImplementedError()
    def remove_option(self, *args, **argd):
        raise NotImplementedError()
    def remove_section(self, *args, **argd):
        raise NotImplementedError()

如果我不把 object 作为混合类来用,调用 SafeConfigParser 的 __init__ 方法就会出问题。现在,我知道有更好的方法可以实现我想要的功能,但我现在很好奇:这样做一般来说可以吗?

我的意思是,我想不出有什么理由认为这样不好,但这还是让我有点不安。这种感觉合理吗,还是我只是过于担心了?

1 个回答

2

把这个调用:

super(ConstParser, self).__init__(defaults)

换成:

SafeConfigParser.__init__(self, defaults)

这样就可以正常工作了,而且不需要用到多重继承。

撰写回答