Polymorphism and duck types

1. What is polymorphism: There are many forms of the same thing

# class Animal:
#     pass
#
# class People(Animal):
#     pass
#
# class Dog(Animal):
#     pass
#
# class Pig(Animal):
#     pass

2. Why should there be polymorphism = "What characteristics will polymorphism bring, polymorphism

#    多态性指的是可以在不考虑对象具体类型的情况下而直接使用对象
class Animal: # 统一所有子类的方法
    def say(self):
        print('动物基本的发声频率。。。',end=' ')

class People(Animal):
    def say(self):
        super().say()
        print('嘤嘤嘤嘤嘤嘤嘤')

class Dog(Animal):
    def say(self):
        super().say()
        print('汪汪汪')

class Pig(Animal):
    def say(self):
        super().say()
        print('哼哼哼')
obj1=People()
obj2=Dog()
obj3=Pig()


obj1.say()
obj2.say()
obj3.say()    
动物基本的发声频率。。。 嘤嘤嘤嘤嘤嘤嘤
动物基本的发声频率。。。 汪汪汪
动物基本的发声频率。。。 哼哼哼



# 定义统一的接口,接收传入的动物对象
def animal_say(animal):
    animal.say()

animal_say(obj1)
animal_say(obj2)
animal_say(obj3)

3. Duck type

  • It does not depend on inheritance at all, only need to create objects with the same appearance and behavior, and can also use objects regardless of object type
  • The "duck type" advocated by Python
# class Cpu:
#     def read(self):
#         print('cpu read')
#
#     def write(self):
#         print('cpu write')
#
# class Mem:
#     def read(self):
#         print('mem read')
#
#     def write(self):
#         print('mem write')
#
#
# class Txt:
#     def read(self):
#         print('txt read')
#
#     def write(self):
#         print('txt write')
# 了解:
import abc

class Animal(metaclass=abc.ABCMeta): # 统一所有子类的标准
    @abc.abstractmethod
    def say(self):
        pass

# obj=Animal() # 不能实例化抽象类自己

class People(Animal):
    def say(self):
        pass

class Dog(Animal):
    def say(self):
        pass

class Pig(Animal):
    def say(self):
        pass

#
obj1=People()
obj2=Dog()
obj3=Pig()

Guess you like

Origin www.cnblogs.com/chenyoupan/p/12675980.html