我有以下问题:
我尝试创建一个从其他两个类继承的类,每个类都有内部 __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/