Python 教程
/ 多态
多态
函数多态
一个可用于不同对象的 Python 函数的例子是 len() 函数。
字符串
对于字符串,len() 返回字符数:
实例
x = "Hello World!" print(len(x))运行实例 »
点击 "运行实例" 按钮查看在线实例
元组
对于元组,len() 返回元组中的项目数:
实例
mytuple = ("apple", "banana", "cherry")
print(len(mytuple))
运行实例 »点击 "运行实例" 按钮查看在线实例
字典
对于字典,len() 返回字典中的键值对数量:
实例
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
运行实例 »点击 "运行实例" 按钮查看在线实例
类多态
多态经常在类方法中使用,我们可以在其中有多个具有相同方法名的类。
例如,假设我们有三个类: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") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class
for x in (car1, boat1, plane1):
x.move()
运行实例 »点击 "运行实例" 按钮查看在线实例
请看最后的 for 循环。由于多态性,我们可以为所有这三个类执行相同的方法。
继承类多态
那么具有相同名称的子类的类呢?我们可以在那里使用多态吗?
可以。如果我们使用上面的例子并创建一个名为 Vehicle 的父类,并使 Car、Boat、Plane 成为 Vehicle 的子类,则子类将继承 Vehicle 的方法,但可以覆盖它们:
实例
创建一个名为 Vehicle 的类,并使 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") # 创建 Car 对象
boat1 = Boat("Ibiza", "Touring 20") # 创建 Boat 对象
plane1 = Plane("Boeing", "747") # 创建 Plane 对象
for x in (car1, boat1, plane1):
print(x.brand)
print(x.model)
x.move()
运行实例 »点击 "运行实例" 按钮查看在线实例
子类从父类继承属性和方法。
在上面的例子中,您可以看到 Car 类是空的,但它从 Vehicle 继承了 brand、model 和 move()。
Boat 和 Plane 类也从 Vehicle 继承了 brand、model 和 move(),但它们都覆盖了 move() 方法。
由于多态性,我们可以为所有类执行相同的方法。