• Python 【类的多态】


    一.多态

    #类的多态
    
    
    class Animal(object):  #Animal类继承object
    
        def __init__(self,color):
    
            self.color = color
    
        def eat(self):
    
            print("动物在吃!")
    
        def run(self):
    
            print("动物在跑")
    
    
    
    class Cat(Animal):  #Cat继承Aninal  继承[属性和方法]
    
        def eat(self):  #方法重名
            print("猫仔!")
    
    
    class Dog(Animal):  #继承时候,方法重名用子方法
    
        def __init__(self,name,age,color):
            super(Dog,self).__init__(color)  #super表示父类,调用父类的初始化方法
    
            self.name = name
    
            self.age = age
    
        def eat(self):  #方法重名
            print("狗仔!")
    
    
    #多态
    def feed(obj):
        obj.eat()
    
    #对象作为参数传入
    
    an = Animal("")
    cat = Cat("橘黄")
    dog = Dog("小黑",12,"黑色")
    
    feed(an)
    feed(cat)
    feed(dog)

    上面有三种类,Animal类、Cat类、Dog类,三种类中都有共同的方法eat()

    使用方法

    def feed(obj):
        obj.eat()

    将对象当参数传入,对应的所有方法执行

  • 相关阅读:
    屏幕后处理方案
    颜色空间
    汉字编码
    物理引擎的确定性研究
    关于List<T>.Sort方法
    Mono跨平台系统大小端问题
    谜之UnityEngine.Object
    第三方平台隐私条款
    Unity DownloadHandler测试
    了解Xcode Bitcode
  • 原文地址:https://www.cnblogs.com/Crown-V/p/12389380.html
Copyright © 2020-2023  润新知