python多态

多态:

  多态是指事物的多种形态,表现为一个类有不同的子类,不用的子类有不同的行为

  同一个变量,传入不同的子类对象,产生不同的行为

class Animal():
    def eat(self):
        print("动物吃东西")


class Pig(Animal):
    def eat(self):
        print("猪吃猪饲料")

class Dog(Animal):
    def eat(self):
        print("狗吃屎")


class test():
    def animal_eat(self, animal):
        animal.eat()


t = test()
pig = Pig()
dog = Dog()


t.animal_eat(pig)   # 猪吃猪饲料
t.animal_eat(dog)   # 狗吃屎

说明:

1. python是解释型语言,不同于java, python的变量类型在运行时决定,所以python多态不严格依赖于继承,只要有同名的方法即可实现多态,如上面的例子,Dog和Pig类可以不继承Animal类,只要有相同的eat方法就行了

2. 建议使用继承来实现多态

 

posted @ 2020-12-26 21:59  foreast  阅读(558)  评论(0编辑  收藏  举报