Search code examples
pythonpython-3.xoverridingmultiple-inheritance

Proper use of method overriding with multiple inheritance?


Assume I have two classes like Mp3Player, and DVDPlayer and I am going to create a new class MultiPlayer which inherits from both former classes.

Mp3Player and DVDPlayer both have a method with same signature:

class MP3Player:

    def play(self, content):
        print(f'MP3 player is playing {content}')


class DVDPlayer:

    def play(self, content):
        print(f'DVD player is playing {content}')

I want to override the play method in MultiPlayer and I want to be able to call the appropriate super class, based on some conditions.

class MultiPlayer(MP3Player, DVDPlayer):

    def play(self, content):
        if mp3_condition:
            # some how call the play method in MP3Player
        elif dvd_condition:
            # some how call the play method in DVDPlayer
        else:
            print('the given content is not supported')

I cannot use super().play(content) as based on MRO rules it always resolves to play method in MP3Player.

What is the pythonic way of doing such thing?


Solution

  • When you use inheritance, you're saying that the subclass is a type of the parent class, just a more specialized one. This is called an is-a relationship.

    One common example uses animals to illustrate this. Imagine you have three classes: Animal, Cat, and Lion. A lion is a cat, and a cat is an animal, so it makes sense to use inheritance in this context.

    However your situation is different. You have a MultiPlayer class, and by using inheritance, you're saying that it is an MP3 player, and it also is a DVD player.

    This can work, however it's more natural in this case to use composition instead of inheritance. Composition is a has-a relationship instead of is-a, meaning that your MultiPlayer class has an MP3 player inside of it, and it also has a DVD player inside of it, but it is not fundamentally either of those things.