Python——多態

來源:互聯網
上載者:User

標籤:end   exce   調用   特性   問題   filename   toolbar   細節   功能   

    因之前寫的多態 的例子,似乎有點問題,現在重寫改造了一下。

"""多態的特性是調用不同的子類將會產生不同的行為,而無需明確知道這個子類實際上是什麼"""class AudioFile:    def __init__(self, filename):        if not filename.endswith(self.ext): #檢測來自子類的ext變數是否以按指定的格式結尾,如果不是則引發異常(初始化音頻檔案需按指定的格式)            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音頻具體的處理細節        print("play %s music..." % self.filename)class OggFile(AudioFile):    ext = "ogg"    def play(self):        #ogg音頻具體的處理細節        print("play %s music..." % self.filename)class Player:    #這是一個播放器,用於播放不同格式的音頻    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()方法,但每不同格式的音頻檔案所實現的功能是不同的


Python——多態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.