zoukankan      html  css  js  c++  java
  • Python----面向对象---多态与多态性

    一、什么是多态

    多态是同一类事物的多种形态

    例如:

     1 import abc
     2 class Animal(metaclass=abc.ABCMeta): #同一类事物:动物
     3     @abc.abstractmethod
     4     def talk(self):
     5         pass
     6 
     7 class People(Animal): #动物的形态之一:人
     8     def talk(self):
     9         print('say hello')
    10 
    11 class Dog(Animal): #动物的形态之二:狗
    12     def talk(self):
    13         print('say wangwang')
    14 
    15 class Pig(Animal): #动物的形态之三:猪
    16     def talk(self):
    17         print('say aoao')

    二、什么是多态性

    多态性指的是可以在不考虑对象类型的情况下而直接使用对象

    例如:

     1 peo1 = People()
     2 dog1 = Dog()
     3 pig1 = Pig()
     4 
     5 peo1.talk()
     6 dog1.talk()
     7 pig1.talk()
     8 
     9 结果为:
    10 
    11 say hello
    12 say wangwang
    13 say aoao
    更进一步,我们可以定义一个统一的接口来使用
     1 def func(animal):
     2     animal.talk()
     3 
     4 
     5 func(peo1)
     6 func(pig1)
     7 func(dog1)
     8 
     9 结果为:
    10 
    11 say hello
    12 say aoao
    13 say wangwang

    三、多态性的好处

    1.增加了程序的灵活性

      以不变应万变,不论对象千变万化,使用者都是同一种形式去调用,如func(animal)

    2.增加了程序额可扩展性

     通过继承animal类创建了一个新的类,使用者无需更改自己的代码,还是用func(animal)去调用  

    例如:

     1 class Cat(Animal):  # 属于动物的另外一种形态:猫
     2     def talk(self):
     3         print('say miao')
     4 
     5 cat1 = Cat()
     6 
     7 func(cat1)
     8 
     9 结果为:
    10 
    11 say miao
  • 相关阅读:
    Python修改文件内容
    Python实现用户注册到文件
    Postman接口测试
    Linux下安装LoadRunner LoadGenerator
    Loadrunner参数化避免重复数据
    Ta-Lib用法介绍 !
    迭代器 生成器
    深入理解python多进程编程
    python多进程
    python多线程
  • 原文地址:https://www.cnblogs.com/xudachen/p/8608793.html
Copyright © 2011-2022 走看看