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

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

  • 相关阅读:
    MongoDB Driver快速浏览
    字符串方法
    内置函数-sorted()和reversed()
    列表相关
    内置函数-eval()
    内置函数-zip
    内置函数-map
    列表
    内置函数-enumerate
    选择结构与循环结构
  • 原文地址:https://www.cnblogs.com/Crown-V/p/12389380.html
Copyright © 2011-2022 走看看