python中的多态是什么

Polymorphism is a concept of Object Oriented Programming, which means multiple forms or more than one form. Polymorphism enables using a single interface with input of different datatypes, different class or may be for different number of inputs.

多态是面向对象编程的概念,它表示多种形式或一种以上形式。 多态性使单个接口可以使用不同数据类型,不同类别或可能用于不同数量输入的输入。

In python as everything is an object hence by default a function can take anything as an argument but the execution of the function might fail as every function has some logic that it follows.

在python中,由于所有事物都是对象,因此默认情况下,函数可以将任何事物作为参数,但是由于每个函数都有其遵循的逻辑,因此函数的执行可能会失败。

For example,

例如,

len("hello")      # returns 5 as result
len([1,2,3,4,45,345,23,42])     # returns 8 as result

In this case the function len is polymorphic as it is taking string as input in the first case and is taking list as input in the second case.

在这种情况下,函数len是多态的,因为在第一种情况下函数以字符串为输入,在第二种情况下函数以list为输入。

In python, polymorphism is a way of making a function accept objects of different classes if they behave similarly.

在python中,多态是一种使函数接受行为不同的类的方法。

Method overriding is a type of polymorphism in which a child class which is extending the parent class can provide different definition to any function defined in the parent class as per its own requirements.

方法重写是一种多态性,其中扩展父类的子类可以根据其自身的要求为父类中定义的任何函数提供不同的定义。

方法重载 (Method Overloading)

Method overloading or function overloading is a type of polymorphism in which we can define a number of methods with the same name but with a different number of parameters as well as parameters can be of different types. These methods can perform a similar or different function.

方法重载或函数重载是一种多态性,其中我们可以定义许多名称相同但参数数量不同的方法,并且参数可以具有不同的类型。 这些方法可以执行相似或不同的功能。

Python doesn't support method overloading on the basis of different number of parameters in functions.

Python不支持基于函数中不同数量参数的方法重载。

定义多态类 (Defining Polymorphic Classes)

Imagine a situation in which we have a different class for shapes like Square, Triangle etc which serves as a resource to calculate the area of that shape. Each shape has a different number of dimensions which are used to calculate the area of the respective shape.

想象一下一种情况,我们对于正方形,三角形等形状有不同的类,可作为计算该形状面积的资源。 每个形状都有不同数量的尺寸,用于计算各个形状的面积。

Now one approach is to define different functions with different names to calculate the area of the given shapes. The program depicting this approach is shown below:

现在一种方法是用不同的名称定义不同的函数,以计算给定形状的面积。 下面显示了描述此方法的程序:

class Square:side = 5     def calculate_area_sq(self):return self.side * self.sideclass Triangle:base = 5height = 4def calculate_area_tri(self):return 0.5 * self.base * self.heightsq = Square()
tri = Triangle()
print("Area of square: ", sq.calculate_area_sq())
print("Area of triangle: ", tri.calculate_area_tri())

Area of square: 25 Area of triangle: 10.0

正方形面积:25三角形面积:10.0

The problem with this approach is that the developer has to remember the name of each function separately. In a much larger program, it is very difficult to memorize the name of the functions for every small operation. Here comes the role of method overloading.

这种方法的问题在于,开发人员必须分别记住每个函数的名称。 在更大的程序中,很难记住每个小操作的功能名称。 这就是方法重载的作用。

Now let's change the name of functions to calculate the area and give them both same name calculate_area() while keeping the function separately in both the classes with different definitions. In this case the type of object will help in resolving the call to the function. The program below shows the implementation of this type of polymorphism with class methods:

现在,让我们更改函数的名称以计算面积,并为它们赋予相同的名称calculate_area()同时在具有不同定义的两个类中分别保留函数。 在这种情况下,对象的类型将有助于解决对该函数的调用。 下面的程序使用类方法显示了这种多态性的实现:

class Square:side = 5     def calculate_area(self):return self.side * self.sideclass Triangle:base = 5height = 4def calculate_area(self):return 0.5 * self.base * self.heightsq = Square()
tri = Triangle()
print("Area of square: ", sq.calculate_area())
print("Area of triangle: ", tri.calculate_area())

Area of square: 25 Area of triangle: 10.0

正方形面积:25三角形面积:10.0

As you can see in the implementation of both the classes i.e. Square as well as Triangle has the function with same name calculate_area(), but due to different objects its call get resolved correctly, that is when the function is called using the object sq then the function of class Square is called and when it is called using the object tri then the function of class Triangle is called.

正如您在两个类(即SquareTriangle的实现中所看到的那样,该函数具有相同的名称calculate_area() ,但是由于对象不同,因此其调用可以正确解析,也就是说,使用对象sq调用该函数时,调用Square类的函数,并且使用对象tri调用该函数时,将调用Triangle类的函数。

类方法的多态 (Polymorphism with Class Methods)

What we saw in the example above is again obvious behaviour. Let's use a loop which iterates over a tuple of objects of various shapes and call the area function to calculate area for each shape object.

在上面的示例中,我们再次看到了明显的行为。 让我们使用一个循环,该循环遍历各种形状的对象的元组,并调用area函数来计算每个形状对象的面积。

sq = Square()
tri = Triangle()for(obj in (sq, tri)):obj.calculate_area()

Now this is a better example of polymorphism because now we are treating objects of different classes as an object on which same function gets called.

现在,这是一个更好的多态示例,因为现在我们将不同类的对象视为在其上调用相同函数的对象。

Here python doesn't care about the type of object which is calling the function hence making the class method polymorphic in nature.

此处python不在乎调用函数的对象类型,因此实际上使类方法具有多态性。

具有功能的多态 (Polymorphism with Functions)

Just like we used a loop in the above example, we can also create a function which takes an object of some shape class as input and then calls the function to calculate area for it. For example,

就像在上面的示例中使用循环一样,我们还可以创建一个函数,该函数将某个形状类的对象作为输入,然后调用该函数为其计算面积。 例如,

find_area_of_shape(obj):obj.calculate_area()sq = Square()
tri = Triangle()# calling the method with different objects
find_area_of_shape(sq)
find_area_of_shape(tri)

In the example above we have used the same function find_area_of_shape to calculate area of two different shape classes. The same function takes different class objects as arguments and executes perfectly to return the result. This is polymorphism.

在上面的示例中,我们使用了相同的函数find_area_of_shape计算两个不同形状类的面积。 相同的函数采用不同的类对象作为参数,并完美执行以返回结果。 这是多态性。

翻译自: https://www.studytonight.com/python/python-polymorphism

python中的多态是什么

python中的多态是什么_Python中的多态相关推荐

  1. Python基础_第3章_Python中的循环结构

    Python基础_第3章_Python中的循环结构 文章目录 Python基础_第3章_Python中的循环结构 Python中的循环结构 一.回顾分支练习题 1.判断是否为一个合法三角形 2.求世界 ...

  2. Python基础_第5章_Python中的数据序列

    Python基础_第5章_Python中的数据序列 文章目录 Python基础_第5章_Python中的数据序列 Python中的数据序列 一.字典--Python中的==查询==神器 1.为什么需要 ...

  3. python post与get的区别_python中get和post有什么区别

    更多编程教程请到:菜鸟教程 https://www.piaodoo.com/ 友情链接: 高州阳光论坛https://www.hnthzk.com/ 人人影视http://www.sfkyty.com ...

  4. python深复制与浅复制_Python中的深拷贝和浅拷贝详解

    要说清楚Python中的深浅拷贝,需要搞清楚下面一系列概念: 变量-引用-对象(可变对象,不可变对象)-切片-拷贝(浅拷贝,深拷贝) [变量-对象-引用] 在Python中一切都是对象,比如说:3, ...

  5. python运行mcmc为何老出错_python中mcmc方法的实现

    MCMC方法在贝叶斯统计中运用很多,MIT发布的EMCEE是实现的比较好的.介绍页面在下面.源代码中examples里的代码可以帮助理解各种功能,特别是line.py 列出了最小二乘法,最大似然法和M ...

  6. python实例属性与类属性_Python中的类属性和实例属性引发的一个坑-续

    上篇文章Python 中的类属性和实例属性,我们探讨了类属性和实例属性引发的一个小坑.总结了类属性和实例属性的区别如下:类属性可以被类和实例调用,实例属性只能被实例调用 类属性不会随着实例的调用而改变 ...

  7. python计算数组元素的和_python中数组的运算

    Python中进行数组的运算需要调用NumPy包. 其官网是:http://www.numpy.org/​www.numpy.org NumPy是Python语言的一个扩充程序库.它支持高级大量的维度 ...

  8. python中格式化字符串的作用_python中字符串格式化的意义(化妆)

    格式 描述 %%百分号标记 #就是输出一个% %c字符及其ASCII码 %s字符串 %d有符号整数(十进制) %u无符号整数(十进制) %o无符号整数(八进制) %x无符号整数(十六进制) %X无符号 ...

  9. python中 r是什么意思_python中rb含义理解

    Python文件读写的几种模式: r,rb,w,wb 那么在读写文件时,有无b标识的的主要区别在哪里呢? 文件使用方式标识 'r':默认值,表示从文件读取数据 'w':表示要向文件写入数据,并截断以前 ...

  10. python字典是什么的集合_Python中的字典和集合

    文章目录字典1.介绍 2.创建字典 3.字典内元素的访问 4.字典元素的添加.修改.删除 5.关于字典的其它操作 6.字典存储底层原理 集合1.介绍 2.相关操作 3.集合元素的添加 4.移除元素 字 ...

最新文章

  1. 《JavaScript忍者秘籍》——导读
  2. 震惊!html文件注释也会影响运行代码!(werkzeug.routing.BuildError: Could not build url for endpoint)莫名其妙
  3. jira使用教程pdf_需要申请项目?需要开通权限?需要创建流程?刚需教程安排上了!...
  4. java system.out.read_求教Java高手,关于输入流的read的问题,为什么while循环体里面的两个System.out.println没有打印出来?...
  5. 电机的入门之路系列3--直流电机的工作原理
  6. SQL查询语句,怎样查询重复数据
  7. oracle拼接空格错误,oracle运维故事 一个空格引发的血案
  8. Microsoft SQL Server 2008技术内幕:T-SQL查询---------逻辑查询处理
  9. 知乎高赞:985计算机视觉毕业后找不到工作怎么办?怒刷leetcode,还是另寻他路?...
  10. webpack 加载html模板,Webpack:从html模板加载图像
  11. 灵悟礼品网上专卖店——新建数据库
  12. 修改服务器linux的yum源为阿里源yum源
  13. 计算机组装硬件配置清单,组装电脑配置清单
  14. 大数据技术之云数据库
  15. AI - H2O - 安装与运行
  16. 运行mysql时,提示Table ‘performance_schema.session_variables’ doesn’t exis
  17. 电脑电源怎么选择,备战40系功耗升级之战
  18. 码农:听新来领导说桌面乱的代码也肯定不整洁,我偷偷收拾了工位
  19. C语言结构体大小计算
  20. ORA-27101异常处理

热门文章

  1. 学计算机专业笔记本买多大尺寸的好,计算机专业用多大大小的笔记本
  2. 最全PyCharm 教程
  3. 智慧工地施工数字化平台让工程项目管理更轻松
  4. Javascript如何修改数组长度?
  5. 数据库笔记-sql执行顺序以及检索优先级
  6. shell命令-pushd和popd
  7. python画黑白线条_Python实现手绘图效果实例分享
  8. ipad air2 java开发_iPad Air 4 和 iPad Pro 2020,谁更具竞争力?
  9. html网页设计中加横线,HTML:让网页超链接拥有多姿多彩的下划线(2)-网页设计,HTML/CSS...
  10. 聊聊Keras的特点及其与其他框架的关系