在同一方法中使用两个父方法

时间:2018-04-02 20:03:36

标签: python python-3.x multiple-inheritance

我有一个名为 Cyborg 的类,它继承自另外两个类:人类机器人。 假设两个父母有自己的方法 Talk(),我可以从 Cyborg 孩子中调用这两种方法吗?例如:

class Cyborg(Human, Robot):
    def Talk(self):
        human_properties = Human.Talk()
        robot_properties = Robot.Talk()
        return human_properties + robot_properties

super()方法无法解决该问题。

3 个答案:

答案 0 :(得分:3)

如果您正确实现了继承图,可以使用super完成此操作。为此,HumanRobot都需要一个可以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!

答案 1 :(得分:1)

使用super(),您将在MRO链上获取同名的第一个方法,但不是两者(除非拾取的方法单独调用super())。如果您想要选择它们,则必须手动调用它们并明确传递self参考:

class Cyborg(Human, Robot):
    def Talk(self):
        human_properties = Human.Talk(self)
        robot_properties = Robot.Talk(self)
        return human_properties + robot_properties
无论如何,我建议不要使用多重继承 - 虽然很有用,但在极少数情况下是不可替代的,它带来了很多陷阱,处理它只是不值得......

答案 2 :(得分:0)

不是将Talk视为方法,而是将其作为classmethod实现,从而无需首先继承:

class Human:
   @classmethod
   def Talk(cls, *args):
      return 

class Robot:
  @classmethod
   def Talk(cls, *args):
      return

class Cyborg:
  def Talk(self):
     return Human.Talk() + Robot.Talk()