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 著

  • 相关阅读:
    3Sum Closest
    二叉树的下一个结点
    数组中重复的数字
    不用加减乘除做加法
    和为S的连续正数序列
    数组中只出现一次的数字
    求二叉树的是否为平衡二叉树
    由一道很简单的求两条链表的第一个公共节点的问题引发的思考
    第14章 网络编程
    第13章 文档与串行化
  • 原文地址:https://www.cnblogs.com/brightyuxl/p/8850049.html
Copyright © 2011-2022 走看看