Python super() with multiple inheritance
假设我想创建
如果我声明
谢谢。
编辑:
我需要"求解"的类示例是这样构造的(为了简洁,简化并跳过了非必需的方法):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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) |
我现在需要做的是实现一个类,它将执行
1 2 3 4 5 6 7 | 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?* |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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() |
这实际上是一个非常有趣的问题。我认为语言中不会有任何允许这样做的特性。您基本上想要做的是使用语言中的方法解析来调用两个方法,其中方法解析总是解析一个方法。因此,这是不可能的。如果您想调用两个独立的方法,您需要自己显式地调用它。