Python 中的多态性

2024 年 8 月 29 日 | 4 分钟阅读

什么是多态? 多态指的是拥有多种形式。多态是一个编程术语,指的是使用相同的函数名称,但具有不同的签名,用于多种类型。

内置多态函数的示例

输出

10
4

用户定义多态函数的示例

输出

29
597

类方法的多态

以下是一个关于 Python 如何以相同方式使用不同类型类的示例。创建了迭代多个对象的 for 循环。接下来,在不关心每个对象属于哪个类的情况下调用方法。这些方法假设存在于每个类中。

示例

输出

Javatpoint is a website out of many availabe on net.
Python is out of many topics about technology on Javatpoint.
Javatpoint is an developed website.
Pinkvilla is a website out of many availabe on net.
Celebrities is out of many topics.
pinkvilla is a developing website.

继承的多态

多态允许我们在 Python 中定义与父类中方法相同的方法。在继承中,父类的方法被传递给子类。有可能更改子类从父类继承的方法。当父类继承的方法不适合子类时,这一点尤其有用。我们在子类中重新实现这些方法。这称为方法重写

示例

输出

There are multiple types of birds in the world.
Many of these birds can fly but some cannot.
There are multiple types of birds in the world.
Sparrows are the bird which can fly.
There are multiple types of birds in the world.
Ostriches are the birds which cannot fly.

函数和对象的 polymorphisms

我们还可以创建可以接受任何对象的函数。这实现了多态。让我们以以下示例为例:让我们创建一个名为“func()”的函数,它将接受一个名为“obj”的对象。即使我们使用名称“obj”,任何已实例化的对象都将能够调用此函数。接下来,我们让函数能够处理传递给它的“obj”对象。让我们调用这三个方法 websites()、topic() 和 type()。它们都定义在类'xyz'和'PQR'中。如果还没有'xyz'和'PQR'类的实例,让我们创建它们。然后我们可以使用相同的函数 func() 调用它们的行为。

示例

输出

Javatpoint is a website out of many availabe on net.
Python is out of many topics about technology on Javatpoint.
Javatpoint is a developed website.
Pinkvilla is a website out of many availabe on net. .
Celebrities is out of many topics.
pinkvilla is a developing website.

代码:使用函数实现多态

输出

Javatpoint is a website out of many availabe on net.
Python is out of many topics about technology on Javatpoint.
Javatpoint is a developed website.
Pinkvilla is a website out of many availabe on net. .
Celebrities is out of many topics.
pinkvilla is a developing website.