Python super()具有多重继承

时间:2014-05-13 13:14:57

标签: python oop inheritance python-3.x super

我想说我要创建SomeClass,它继承自两个类:

class SomeClass(InheritedClass1, InheritedClass2):

InheritedClass1InheritedClass2都有方法,名称相同,名为performLogic

如果我声明super().peformLogic(),我将仅从第一个参数/继承类获得结果。我需要两者的结果,所以我的问题是,有没有办法从InheritedClass1调用方法,然后使用InheritedClass2super()调用?

感谢。

编辑:

我需要解决的类示例'是这样构造的(为简洁而简化,跳过非必要的方法):

class One:
    ...

    def getOutput(self):
        self.output = self.performLogic()
        return self.output

class Two(One):
    ...

    def getFirstValue(self):
        return input()

    def getSecondValue(self):
        return input()

class Three(Two):
    ...

    def performLogic(self):
        (some logic performation based on inputs from class Two methods)

class Four(Two):
    ...

    def performLogic(self):
        (some *different* logic performation based on inputs from class Two methods)

我现在需要做的是实现一个类,它将执行class Threeclass Four的逻辑,但只有一对输入值。所以我宣布:

class Five(Three,Four):
    def performLogic(self):
        *and here I got stuck*
        *super().performLogic() will ask me for input values and returns the
        *result of class Three's performLogic()*
        *but what of class Four, I need the result of it's performLogic() with
        *a single pair of input values, too?*

2 个答案:

答案 0 :(得分:4)

super不是在父基类中调用方法的通用替代品;它要求合作设计课程。这意味着每个类都需要调用super().performLogic,以防万一它不是某个类的MRO的最后一个元素。 最终,在方法解析顺序的末尾必须有一些类不能调用super().peformLogic(),因为它是列表中的 last 类,或者下一个调用将被委托给一个类(如object),它没有定义performLogic。在这种情况下,您必须自己提供这样的根类。

class LogicPerformer:
    def performLogic(self):
        # No call to super; the buck stops here, because object
        # doesn't have this method
        print("In LogicPerformer")

class InheritedClass1(LogicPerformer):

    def performLogic(self):
        print("In InheritedClass1")
        super().performLogic()

class InheritedClass2(LogicPerformer):

    def performLogic(self):
        print("In InheritedClass1")
        super().performLogic()

class SomeClass(InheritedClass1, InheritedClass2):

    def performLogic(self):
        print("In SomeClass")
        super().performLogic()

a = SomeClass()
print(SomeClass.__mro__)
a.performLogic()

答案 1 :(得分:0)

这实际上是一个非常有趣的问题。我认为语言中没有任何功能允许这样做。你基本上想要做的是在语言中使用方法解析来调用两种方法,其中方法解析总是解决一个方法。因此,这是不可能做到的。如果你想调用两个单独的方法,你需要自己明确地做。

相关问题