"""
多态的特性是调用不同的子类将会产生不同的行为,而无需明确知道这个子类实际上是什么
"""
class AudioFile:
def __init__(self, filename):
if not filename.endswith(self.ext): #检测来自子类的ext变量是否以按指定的格式结尾,如果不是则引发异常
raise Exception("Invalid file format")
self.filename = filename
class MP3File(AudioFile):
ext = "mp3"
def play(self):
print("play %s music..." % self.filename)
class WavFile(AudioFile):
ext = "wav"
def play(self):
print("play %s music..." % self.filename)
class OggFile(AudioFile):
ext = "ogg"
def play(self):
print("play %s music..." % self.filename)
if __name__ == '__main__':
ogg = OggFile("myfile.ogg")
ogg.play()
mp3 = MP3File("myfile.mp3")
mp3.play()
wav = WavFile("myfile.wav")
wav.play()
#看起来好像都是调用了同一个play()方法,但实现的功能是不同的
原文地址:http://blog.51cto.com/freshair/2058610