Python中的多重继承与super()
假设我想创建一个叫做 SomeClass
的类,它同时继承自两个类:
class SomeClass(InheritedClass1, InheritedClass2):
这两个类 InheritedClass1
和 InheritedClass2
都有一个同名的方法,叫做 performLogic
。
如果我使用 super().performLogic()
,我只会得到第一个继承类的结果。我需要两个类的结果,所以我想问,有没有办法先调用 InheritedClass1
的方法,然后再调用 InheritedClass2
的方法,使用 super()
来实现?
谢谢。
编辑:
我需要“解决”的类的例子是这样构建的(为了简洁,省略了一些不重要的方法):
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 Three
和 class 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().performLogic()
,要么是因为它在列表中是最后一个,要么是因为下一个调用会转到一个不定义 performLogic
的类(比如 object
)。在这种情况下,你需要自己提供这样一个根类。
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()