python--polymorphism

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.