多态

什么是多态?

  同一种事物的多种形态

为何要用多态

  多态性: 指的就是可以在不用考虑对象具体类型的前提下直接使用对象下的方法

如何用多态?

import abc

class Animal(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def speak(self):
        pass

# Animal() # 父类不能实例化,因为父类本身就是用来制定标准的
class People(Animal):
    def speak(self):
        print('say hello')
        
class Dog(Animal):
    def speak(self):
        print('汪汪汪')

class Pig(Animal):
    def speak(self):
        print('哼哼哼')
        
peo=People()
dog1=Dog()
pig1=Pig()
结果:say hello
   汪汪汪
   哼哼哼

另一种调用:

def speak(animal):
animal.speak()

speak(peo)
speak(dog1)
speak(pig1)

结果同上
#再看一个
class Memory:
    def read(self):
        print('mem read')

    def write(self):
        print('mem write')

class Disk:
    def read(self):
        print('disk read')

    def write(self):
        print('disk write')

class Cpu:
    def read(self):
        print('cpu read')

    def write(self):
        print('cpu write')


obj1=Memory()
obj2=Disk()
obj3=Cpu()

obj1.read()
obj2.read()
obj3.read()

结果:
mem read
disk read
cpu read
原文地址:https://www.cnblogs.com/TF511/p/9845365.html