多态性 Python 举例说明

⚡ 智能摘要

多态性 Python 它允许单个接口处理不同类型的对象,因此同一个方法或运算符会根据对象的不同而表现出不同的行为。这种特性体现在运算符重载、内置函数、用户自定义方法以及跨对象的继承上。 Python 程式。

  • 🔘 定义: 多态性意味着“多种形式”,允许一个接口作用于不同的数据类型或类。
  • ☑️ OperaTor过载: + 运算符可以对数字进行加法运算,但也可以连接字符串,这体现了运算符的多态性。
  • 内置功能: len() 等函数可以同时用于字符串、列表和字典。
  • 🧪 用户自定义方法: 不同形状的类可以共享类似 area() 和 perimeter() 的方法名。
  • 🛠️ 遗产: 方法重写允许子类在运行时重新定义父类的方法。
  • 🤖 人工智能相关性: 机器学习库会在不同的模型之间重用共享接口,例如 fit() 和 forward()。

多态性 Python

什么是多态?

多态性可以定义为以多种不同形式出现的条件。它是 Python 编程中,在 Python 可以以不同的方式使用。它允许程序员在派生类中定义多个方法,并且它具有与父类中相同的名称。此类场景支持方法重载 Python.

多态性 Opera职权范围

中的运算符 Python 有助于执行数学和其他一些编程任务。例如,“+”运算符有助于在两个整数类型之间执行加法 Python,同样地,相同的运算符也有助于连接字符串 Python 节目。

让我们以 + (加号)为例 运算符 Python 显示多态性的应用 Python 如下图所示:

Python Code:

p = 55
q = 77
r = 9.5
g1 = "Guru"
g2 = "99!"
print("the sum of two numbers",p + q)
print("the data type of result is",type(p + q))
print("The sum of two numbers",q + r)
print("the data type of result is", type (q + r))
print("The concatenated string is", g1 + g2)
print("The data type of two strings",type(g1 + g2))

输出:

the sum of two numbers 132
the data type of result is <class 'int'>

The sum of the two numbers 86.5
the data type of result is <class 'float'>

The concatenated string is Guru99!
The data type of two strings <class 'str'>

上面的例子也可以看作是运算符重载的例子。

用户定义方法中的多态性

用户定义的方法 Python 编程语言是用户创建的方法,使用关键字def和函数名来声明。

多态性 Python 编程语言是通过方法重载和重写来实现的。 Python 在子类和父类中用 def 关键字定义具有相同名称的方法。

让我们来看以下示例:-

Python Code:

from math
import pi
class square:
    def __init__(self, length):
    self.l = length
def perimeter(self):
    return 4 * (self.l)
def area(self):
    return self.l * self.l
class Circle:
    def __init__(self, radius):
    self.r = radius
def perimeter(self):
    return 2 * pi * self.r
def area(self):
    return pi * self.r * * 2
# Initialize the classes
sqr = square(10)
c1 = Circle(4)
print("Perimeter computed for square: ", sqr.perimeter())
print("Area computed for square: ", sqr.area())
print("Perimeter computed for Circle: ", c1.perimeter())
print("Area computed for Circle: ", c1.area())

输出:

Perimeter computed for square:  40
Area computed for square:  100
Perimeter computed for Circle:  25.132741228718345
Area computed for Circle:  50.26548245743669

在上面的代码中,有两个用户定义的方法,perimeter和area,分别定义在circle和square类中。

如上所示,圆形类和方形类都调用相同的方法名,显示出多态性的特征来提供所需的输出。

函数中的多态性

内置函数 Python 被设计并兼容执行多种数据类型。 Pythonlen() 是关键的内置函数之一。

它支持多种数据类型:列表、元组、字符串和字典。len() 函数返回与这些数据类型相对应的明确信息。

下图展示了如何将多态性应用于 Python 与内置函数相关:–

函数中的多态性

以下程序有助于说明多态性在 Python -

Python Code:

print ("The length of string Guru99 is ",len("Guru99"))
print("The length of list is ",len(["Guru99","Example","Reader"]))
print("The length of dictionary is ",len({"Website name":"Guru99","Type":"Education"}))

输出:

The length of string Guru99 is 6
The length of the list is 3
The length of the dictionary is 2

函数中的多态性

在上面的例子中,len() 函数 Python 分别对字符串、列表和字典数据类型执行多态性。

多态性和继承

继承 Python 可以定义为编程概念,其中定义的子类从另一个基类继承属性 Python.

有两个关键 Python 称为方法覆盖和方法重载的概念。

  • 在方法重载中, Python 提供创建具有相同名称的方法的功能,以在给定的代码段中执行或执行不同的功能。它允许重载方法并使用它们以更简单的方式执行不同的任务。
  • 在方法重写中, Python 覆盖父类和子类中共享相似名称的值。

让我们来看看以下多态性和继承的例子,如下所示:-

Python Code:

class baseclass:
    def __init__(self, name):
    self.name = name
def area1(self):
    pass
def __str__(self):
    return self.name
class rectangle(baseclass):
    def __init__(self, length, breadth):
    super().__init__("rectangle")
self.length = length
self.breadth = breadth
def area1(self):
    return self.length * self.breadth
class triangle(baseclass):
    def __init__(self, height, base):
    super().__init__("triangle")
self.height = height
self.base = base
def area1(self):
    return (self.base * self.height) / 2
a = rectangle(90, 80)
b = triangle(77, 64)
print("The shape is: ", b)
print("The area of shape is", b.area1())
print("The shape is:", a)
print("The area of shape is", a.area1())

输出:

The shape is: a triangle
The area of a shape is 2464.0

The shape is: a rectangle
The area of a shape is 7200

在上面的代码中,方法具有相同的名称,定义为 init 方法和 area1 方法。然后使用 square 和 rectangle 类的对象调用这两个方法来执行不同的任务,并提供正方形和矩形面积的输出。

类方法的多态性

此 Python 编程使程序员能够使用类方法实现多态性和方法重载。不同的类 Python 可以有跨同名声明的方法 Python 码。

In Python,可以定义两个不同的类。一个是子类,它从另一个定义的类(称为父类)派生出属性。

下面的例子说明了类方法的多态性概念:-

Python Code:

class amazon:
    def __init__(self, name, price):
    self.name = name
self.price = price
def info(self):
    print("This is product and am class is invoked. The name is {self.name}. This costs {self.price} rupees.")
class flipkart:
    def __init__(self, name, price):
    self.name = name
self.price = price
def info(self):
    print(f "This is product and fli class is invoked. The name is {self.name}. This costs {self.price} rupees.")
FLP = flipkart("Iphone", 2.5)
AMZ = amazon("Iphone", 4)
for product1 in (FLP, AMZ):
    product1.info()

输出:

This is a product, and fli class is invoked. The name is iPhone, and this costs 2.5 rupees.
This is a product, and am class is invoked. The name is iPhone, and this costs 4 rupees.

在上面的代码中,两个不同的类,分别为 flipkart 和 amazon,使用相同的方法名称 info 和 init 来提供产品的相应价格报价,并进一步说明了多态性的概念 Python.

方法重载和编译时多态性之间的区别

在编译时多态性中, Python 程序解析调用。编译时多态性是通过方法重载实现的。

此 Python 编译器不会在运行时解析多态性调用。它也被归类为方法覆盖,其中相同的方法带有相似的签名或属性,但它们构成不同类的一部分。

常见问题

鸭子ping 让 Python 判断一个对象是否合格,应该看它提供的方法,而不是它的类类型。如果一个对象拥有所需的方法,它就能正常工作,这遵循“如果它走起来像鸭子,叫起来像鸭子,那它就是鸭子”的原则。

传统上并非如此。当两个方法名称相同时,以最后定义的为准。 Python 相反,它使用默认参数、可变长度 *args 或 functools.singledispatch 装饰器来模拟重载,从而在单个函数中处理不同的参数类型。

ABStrac来自 abc 模块的基类声明了所有子类都必须实现的方法。它们强制执行共享接口,因此不相关的子类可以以多态方式使用。 Python 保证每一种方法都具备所需的功能。

多态性提高了代码的可重用性、灵活性和可扩展性。一个函数或接口可以处理多种对象类型,这减少了代码重复,简化了维护,并且允许您添加新类而无需重写已使用它们的代码。

是的。通过鸭子泰ping实现相同方法的不相关类可以互换使用,而无需任何共同的父类。 Operator 重载和内置函数(如 len())也提供了无需继承的多态性。

当一个函数处理字符串、列表或自定义对象时,多态性就会出现;当数据库驱动程序跨引擎公开单个 API 时,多态性就会出现;当 GUI 工具包中许多小部件共享通过一个接口调用的 draw() 或 update() 方法时,多态性就会出现。

AI框架依赖于多态性。在Py中Torch,每个模型都继承了 nn.Module 并重写了 forward();在 scikit-learn 中,估计器共享 fit() 和 predict() 方法,因此不同的算法通过一个一致、可互换的接口运行。

是的。GitHub Copilot 和智能 AI 助手会生成鸭子类型函数,并给出绝对值建议。trac根据简短提示,创建基类并将重复方法重构为多态设计。 Rev查看输出结果,确认逻辑和接口是否正确。

总结一下这篇文章: