zoukankan      html  css  js  c++  java
  • 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 著

  • 相关阅读:
    功能测试用例大全
    相对最完整的软件测试工具手册
    测试用例的评审
    黑盒测试学习笔记-(深圳文鹏)
    Llinux:ubuntu常用命令(深圳文鹏)
    HDU-4857(拓扑排序)
    HDU-3665(单源最短路)
    HDU-3661(贪心)
    HDU-2059龟兔赛跑(基础方程DP-遍历之前的所有状态)
    HDU-1047(DP-二进制状态压缩)
  • 原文地址:https://www.cnblogs.com/brightyuxl/p/8850049.html
Copyright © 2011-2022 走看看