Python 3.x : Avoid overwriting of same methods from different inherited classes

标签 python python-3.x multiple-inheritance

我有以下问题:

我尝试创建一个从其他两个类继承的类,每个类都有内部 __setitem__ 方法。作为 featuresB 初始化的一部分,我想调用一个 createFeaturesB 函数来为该类创建内容。不幸的是,从最后两个 print 语句的输出可以看出,__setitem__ 的调用引用了 featuresA.__setitem__

class featuresA():
    def __init__(self):
        self._dictA      = dict()
        return
    def __setitem__(self, key, value):
        self._dictA[key] = value
        return

class featuresB():
    def __init__(self):
        self._dictB      = dict()
        self.createFeaturesB()
        return
    def __setitem__(self, key, value):
        self._dictB[key] = value
        return
    def createFeaturesB(self):
        for i in range(3):
            self[i] = i**2
        return

class C(featuresA, featuresB):
    def __init__(self):
        featuresA.__init__(self)
        featuresB.__init__(self)
        return

c = C()
print(c._dictB) #returns: {}
print(c._dictA) #returns: {0: 0, 1: 1, 2: 4}

如何避免这两个方法被覆盖?

最佳答案

有时最好先考虑一下您是否正确构建了继承图。在这种情况下,颠倒继承顺序即可解决问题。

class C(featuresB, featuresA): # Reverse the inheritance order
    def __init__(self):
        featuresA.__init__(self)
        featuresB.__init__(self)

c = C()
c._dictB # {0: 0, 1: 1, 2: 4}
c._dictA # {}

尽管一般来说,从尚未实现支持它的类中获得多重继承是有问题的。您可能需要更新 featuresA 以使用 super

class featuresA():
    def __init__(self):
        self._dictA      = dict()
        super().__init__()

    def __setitem__(self, key, value):
        self._dictA[key] = value
        super().__setitem__(key, value)

class featuresB():
    def __init__(self):
        self._dictB      = dict()
        self.createFeaturesB()

    def __setitem__(self, key, value):
        self._dictB[key] = value

    def createFeaturesB(self):
        for i in range(3):
            self[i] = i**2

class C(featuresA, featuresB):
    def __init__(self):
        super().__init__()

c = C()
c._dictB # {0: 0, 1: 1, 2: 4}
c._dictA # {0: 0, 1: 1, 2: 4}

在更复杂的情况下,您希望从每个类中挑选某些方法,那么您需要重建类图,重写您的基类。多重继承是一个强大的工具,但它并不是魔法。它将一些责任委托(delegate)给开发人员。

关于Python 3.x : Avoid overwriting of same methods from different inherited classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831552/

相关文章:

jquery - 使用ajax上传时Django文件丢失

c++ - 在多个基类之间重载成员函数

c++ - 多重继承解决抽象类

python - Twitter 身份验证在 Twython 2.3.4 上失败,错误为 : 401, 无法验证 oauth 签名和 token

python - 从 Tensorflow 中的 tf.matmul(tf.transpose(A), A) 获取对角线元素

python - 从多个类型字符串输出整数列表的最佳解决方案

delphi - 如何将不同的类封装在一个类中并保持其独特的方法? (delphi中的多重继承?)

python - 如何使用 python 获取 Excel 工作表的 "Total Editing Time"属性?

python-3.x - 如何检查连接到 GRPC 服务器的客户端

Python 3 html模块导入错误?