假设用程序播放音频。一个播放器对象(mediaplayerobject)创建AudioFile 对象,执行 play 方法。play()方法负责解码音频文件,并播放,其行为可简单 描述为audio-file.play()。但解码音频文件,需要根据不同的文件使用不同的 算法,wav,mp3,wma,ogg,显然不能用同一种算法解码。如果,要为每种文件定 义一个play()方法,那得定义很多少个方法?!而且,随着技术发展,出现新的 音频文件格式怎么办,定义多少个方法够用呢?使用继承和多态可以简化设计。 思路是这样的,每种格式用 AudioFile 的一个子类表示,如 WavFile、MP3File 等。每个子类都有自己的play()方法,但该方法根据不同子类实现不同的解码算 法和播放功能。而播放器对象永远不必知道 AudioFile 指的是哪个子类,播放器 只需调用play()方法,让对象的多态机制处理具体的解码播放即可。
本练习涵盖继承、覆盖、多态技术
# polymorphism exercise
class AudioFile:
def __init__(self, filename):
if not filename.endswith(filename[-3:]):
raise Exception("Invalid file format")
self.filename = filename self.ext = filename[-3:]
def play(self):
print("Now an audio file is going to play...{} as {}". format(self.filename, self.ext))
class MP3File(AudioFile):
def __init__(self, filename):
super().__init__(filename)
self.ext = "mp3"
def play(self):
# super().play()
print("playing {} as mp3".format(self.filename))
class WavFile(AudioFile):
def __init__(self, filename):
super().__init__(filename)
self.ext = filename[-3:]
def play(self):
print("playing {} as {}".format(self.filename, self.ext))
class OggFile(AudioFile):
def __init__(self, filename): super().__init__(filename)
self.ext = filename[-3:]
def play(self):
print("playing {} as ogg".format(self.filename))
class FlacFile(AudioFile):
def __init__(self,filename): super().__init__(filename)
self.ext = filename[-3:]
def play(self):
print("playing {} as flac".format(self.filename))
print("===split line ===")
mp3 = MP3File("myfile.mp3")
mp3.play()
print("===split line ===")
wav = WavFile("myfile.wav")
wav.play()
print("===split line ===")
not_an_mp3 = MP3File("myfile.nothing")
not_an_mp3.play()
print(’Clearly, it is going to cause decoding error!’)
print("===split line ===")
flac = FlacFile("myfile.flac")
flac.play()
print(flac.ext)
print("===split line ===")
print(’----------another split line------------’)
afile = MP3File("myfile.mp3")
bfile = WavFile("myfile.wav")
cfile = FlacFile("myfile.flac")
music_file = [afile, bfile, cfile]
for x in music_file:
x.play()
来源:CSDN
作者:Louise_Trender
链接:https://blog.csdn.net/Louise_Trender/article/details/103505887