【发布时间】:2019-12-24 03:21:28
【问题描述】:
假设我有两个类,如 Mp3Player 和 DVDPlayer,我将创建一个新类 MultiPlayer,它继承自之前的两个类。
Mp3Player 和 DVDPlayer 都有一个签名相同的方法:
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}')
我想重写MultiPlayer 中的play 方法,并且我希望能够根据某些条件调用适当的超类。
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')
我不能使用super().play(content),因为它总是解析为MP3Player 中的play 方法。
做这种事情的pythonic方式是什么?
【问题讨论】:
-
我不确定在这种情况下使用多重继承是否有意义。也许可以改用一种包装器模式,其中
MultiPlayer具有内部属性,它们是MP3Player和DVDPlayer的实例。 -
是的,这是可能的。但我想了解python中的多重继承,我想知道这种情况是否发生,处理它的正确方法是什么。
标签: python python-3.x overriding multiple-inheritance