zoukankan      html  css  js  c++  java
  • 多态

    什么是多态?

      同一种事物的多种形态

    为何要用多态

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

    如何用多态?

    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
  • 相关阅读:
    第四次上课 PPT作业
    大道至简 读后感④
    第三次上课 PPT 课后测试
    大道至简 读后感③
    Java 02 课后作业
    Java 多个数字相加算法
    大道至简 读后感②
    wpf控件
    一个简单的prism mef例子
    c#弱事件(weak event)
  • 原文地址:https://www.cnblogs.com/TF511/p/9845365.html
Copyright © 2011-2022 走看看