03.1 鸭子类型与多态

135 阅读1分钟

目录

鸭子类型

大家可以去看看这个https://blog.csdn.net/reuxfhc/article/details/80036691
定义类时,各个类有一样的方法,不需要去指定继承一个类

代码

# 鸭子类型
# 定义类时,各个类有一样的方法,不需要去指定继承一个类
#

class Cat:
    def say(self):
        print("cat saying 喵.")


class Dog:
    def say(self):
        print("dog saying 汪.")


class Duck:
    def say(self):
        print("duck saying 嘎.")


animal_list = [Cat, Dog, Duck]
for animal in animal_list:
    animal().say()
    """
    cat saying 喵.
    dog saying 汪.
    duck saying 嘎.
    """