Search code examples
pythonpython-3.xmultiple-inheritance

Use both parents methods in the same method


I have a class called Cyborg and it inherits from another two classes: Human and Robot. Supposing the two parents have their own method Talk(), can I call these two methods from the Cyborg child? For example:

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

The super() method do not resolve that problem.


Solution

  • Using super() you will pick up the first method of the same name up the MRO chain, but not both (unless the picked up method calls super() on its own). If you want to pick them both you'll have to call them manually and explicitly pass the self reference:

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

    I'd advise against multiple inheritance anyway - while nifty and useful, and in very rare cases irreplaceable, it comes with so many pitfalls that dealing with it is just not worth it...