在Python面向对象编程中,多态(Polymorphism)指的是同一个函数或方法可以针对不同数据类型或类,呈现出不同的行为。简单说,“一张方法名,能在多处使用”。本文将介绍函数多态和类多态的常见场景及用法。
1. 函数多态:相同函数名处理不同类型
在Python里,len()
函数就是一个好例子。它可以计算字符串、列表、字典等各种容器的长度:
# 计算字符串长度
x = "Hello World!"
print(len(x)) # 12
# 计算元组(Tuple)长度
mytuple = ("apple", "banana", "cherry")
print(len(mytuple)) # 3
# 计算字典(Dictionary)中键值对数量
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict)) # 3
虽然len()
只是一个函数名,但针对字符串、元组、字典等类型却执行了不同的底层逻辑,这就体现了多态的特性。
2. 类多态:相同方法,不同实现
在类(Class)中,多态往往表现为同名方法在不同类里有不同的实现。
2.1 简单示例
假设我们有三个类:Car、Boat和Plane,它们都定义了move()
方法,但实现不同:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang")
boat1 = Boat("Ibiza", "Touring 20")
plane1 = Plane("Boeing", "747")
for vehicle in (car1, boat1, plane1):
vehicle.move()
# 分别输出: Drive!, Sail!, Fly!
这里的move()
方法在不同类里表现各异。当我们统一调用vehicle.move()
时,就实现了多态。
2.2 与继承结合
多态常与继承结合使用,比如我们让Car、Boat、Plane都继承自同一个父类Vehicle:
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Move!")
class Car(Vehicle):
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang")
boat1 = Boat("Ibiza", "Touring 20")
plane1 = Plane("Boeing", "747")
for v in (car1, boat1, plane1):
print(v.brand, v.model)
v.move()
这里Car不重写move()
,就用到Vehicle里的默认实现;Boat和Plane则重写move实现各自的移动方式。
3. 为什么需要多态
多态可以带来以下好处:
- 让函数/方法对各种类型更具包容性,无需写多种函数名
- 在继承体系里,不同子类可以用同名方法执行不同逻辑
- 使代码更简洁、更易扩展:只要一个入口,不用频繁做类型判断
4. 关键点总结
- 多态指“同名方法/函数”可根据对象类型/类的不同而表现不同。
- 常见的例子:
len()
对不同类型对象进行长度计算。 - 类多态:不同子类重写同一个父类方法,如Car、Boat、Plane都实现
move()
。 - 与继承结合能让代码结构更清晰、可扩展。
通过多态,Python能把“相同方法名,针对不同对象”的操作统一起来,大大减少了对类型的显式判断,让面向对象程序更灵活、更具有可扩展性。