Python面向對象——多態


多態的作用

調用不同的子類將會產生不同的行為。
多態是在繼承上實現的。

圖解多態1

圖解多態2

圖解多態1代碼

class AudioFile:
    def __init__(self, filename):
        if not filename.endswith(self.ext):
            raise Exception("Invalid file format")
        self.filename = filename
        
class MP3File(AudioFile):
    ext = "mp3"
    def play(self):
        print("playing {} as mp3".format(self.filename))
        
class WavFile(AudioFile):
    ext = "wav"
    def play(self):
        print("playing {} as wav".format(self.filename))
        
class OggFile(AudioFile):
    ext = "ogg"
    def play(self):
        print("playing {} as ogg".format(self.filename))

ogg = OggFile("myfile.ogg")
ogg.play()

mp3 = MP3File("myfile.mp3")
mp3.play()

not_an_mp3 = MP3File("myfile.ogg")
not_an_mp3.play()

圖解多態2代碼

(參考https://www.cnblogs.com/luchuangao/p/6739557.html)

#多態:同一種事物的多種形態,動物分為人類,豬類(在定義角度)
class Animal:
    def run(self):
        raise AttributeError('子類必須實現這個方法')
 
 
class People(Animal):
    def run(self):
        print('人正在走')
 
class Pig(Animal):
    def run(self):
        print('pig is walking')
 
 
class Dog(Animal):
    def run(self):
        print('dog is running')
 
peo1=People()
pig1=Pig()
d1=Dog()
 
peo1.run()
pig1.run()
d1.run()

參考:本文參考學習《Python3 Object Oriented Programming》,根據自己理解改編,Dusty Phillips 著


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM