我有一个名为 Cyborg 的类,它继承了另外两个类:Human 和 Robot。 假设两个 parent 有自己的方法Talk(),我可以从Cyborg child 调用这两个方法吗?例如:
class Cyborg(Human, Robot):
def Talk(self):
human_properties = Human.Talk()
robot_properties = Robot.Talk()
return human_properties + robot_properties
super() 方法不能解决这个问题。
最佳答案
如果你正确地实现了你的继承图,这可以用 super
来完成。为此,Human
和 Robot
都需要一个可以Talk
的通用基类。
class Thing:
def Talk(self):
# Things don't talk, but some more complex things may
return ''
class Robot(Thing):
def Talk(self):
return 'I am a computer!\n' + super().Talk()
class Human(Thing):
def Talk(self):
return 'I am an organic being!\n' + super().Talk()
class Cyborg(Human, Robot):
def Talk(self):
return super().Talk()
这是一个会说话的例子。
>>> Cyborg().Talk()
I am an organic being!
I am a computer!
>>> Robot().Talk()
I am a computer!
>>> Human().Talk()
I am an organic being!
关于python - 在同一个方法中使用两个父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49618016/