多态性与鸭子类型

一,多态性

# 示例1:
class Animials:
    def say(self):
        print('动物的发声')

class People(Animials):
    def say(self):
        print('人类:aoe')

class Dog(Animials):
    def say(self):
        print('狗子:汪汪汪')

class Cat(Animials):
    def say(self):
        print('猫咪: 喵喵喵')

people=People()
people.say()
# 人类:aoe

dog=Dog()
dog.say()
# 狗子:汪汪汪

cat=Cat()
cat.say()
# 猫咪: 喵喵喵







# 示例2
class Animials:
    def say(self):
        print('动物的发声',end=' ----> ')

class People(Animials):
    def say(self):
        super().say()
        print('人类:aoe')

class Dog(Animials):
    def say(self):
        super().say()
        print('狗子:汪汪汪')

class Cat(Animials):
    def say(self):
        super().say()
        print('猫咪: 喵喵喵')


people=People()
people.say()
# 动物的发声 ----> 人类:aoe


dog=Dog()
dog.say()
# 动物的发声 ----> 狗子:汪汪汪

cat=Cat()
cat.say()
# 动物的发声 ----> 狗子:汪汪汪






# 示例3
class Animials:
    def say(self):
        print('动物的发声',end=' ----> ')

class People(Animials):
    def say(self):
        super().say()
        print('人类:aoe')

class Dog(Animials):
    def say(self):
        super().say()
        print('狗子:汪汪汪')

class Cat(Animials):
    def say(self):
        super().say()
        print('猫咪: 喵喵喵')


# 注意这里的animal可以为任意值,主要是在people=People()的基础上,调用animal_say(people),即直接调用People下面的say
def animal_say(animal):
    animal.say()


people=People()
animal_say(people)
# 动物的发声 ----> 人类:aoe


多态示例

print(len('hello'))
# 5

print(len([1,2,3]))
# 3

# hello的长度
print('hello'.__len__())
# 5


# 支持列表
print([1,2,3].__len__())
# 3


# 支持字典
print({'a':11,"b":22}.__len__())
# 2




def my_len(val):
    return val.__len__()

print(my_len('morning'))
# 7

print(my_len([1,2,3]))
# 3

print(my_len({'a':1,'b':2}))
# 2

二,鸭子类型

1,定义
只需要制造出外观和行为相同对象,同样可以实现不考虑对象类型而使用对象,这正是Python崇尚的“鸭子类型”(duck typing)

class People:
    def sing(self):
        print('people like to sing')

    def food(self):
        print('people like cooking')

class Cat:
    def sing(self):
        print('cat can not sing')

    def food(self):
        print('cat can not cook')

people=People()
people.sing()
# people like to sing

people.food()
# people like cooking



cat=Cat()
cat.sing()
# cat can not sing

cat.food()
# cat can not cook

#总结:以上People人类和Cat猫咪属于不同的生物,人类会有唱歌和做饭的功能,实际上猫咪没有;但是猫咪也创造出和人类一样的函数属性,也可以一样调用,看起来是一样的,称之为"鸭子类型







2,示例
import abc
class Animals(metaclass=abc.ABCMeta):
    @abc.abstractmethod     # 该装饰器限制子类必须定义有一个名为say的方法
    def say(self):
        print('hello')

class Dog(Animals):         # 但凡继承Animal的子类都必须遵循Animal规定的标准
    def say(self):
        print('from dog')


# 不能调用自己,会报错
# 指定metaclass属性将类设置为抽象类,抽象类本身只是用来约束子类的,不能被实例化
#obj=Animals()

dog=Dog()     #若子类中没有一个名为talk的方法则会抛出异常TypeError,无法实例化
dog.say()
# from dog

你可能感兴趣的:(多态性与鸭子类型)