Because of the polymorphic examples previously written, there seems to be a bit of a problem, now rewrite the makeover.
The "" "polymorphic feature is that invoking different subclasses will produce different behaviors without having to know exactly what the subclass actually is," "Class audiofile: def __init__ ( Self, filename): if not filename.endswith ( Self.ext): #检测来自子类的ext变量是否以按指定的格式结尾, throws an exception if it is not (initialize the audio file in the specified format) raise exception ("Invalid file format") self.filename = filenameclass mp3file (AudioFile): ext = "MP3" def play (self): #mp3音频具体的处理细节 print ("Play %s music ..." % self.filename) Class wavfile (AudioFile): ext = "wav" def play (self): #wav音频具体的处理细节 &nbSp;print ("Play %s music ..." % self.filename) class oggfile (AudioFile): ext = "Ogg" def play (self): #ogg音频具体的处理细节 print ("Play %s music ... " % self.filename) class player: #这是一个播放器 for playing different formats of audio def start (Self, audio): print ("Initialize {0} format audio files ". Format (audio.ext)) print ("audio file: {0} playing". Format (audio.filename)) audio.play () if __name__ == ' __main__ ': #创建一个播放器 player = player () #创建3个不同格式的音频文件 ogg = oggfile ("Hello.ogg") mp3 = mp3file ("Free abc.mp3") wav = Wavfile ("Love.wav") #播放器播放音乐 player.start (OGG) #看起来好像都是调用了同一个play () method, but the functionality implemented for each audio file in a different format is different
python--polymorphism