Python 多态
“多态”这个词的意思是“多种形式”,在编程中,它指的是具有相同名称的方法/函数/运算符,可以对许多对象或类执行。
函数多态
一个可以用于不同对象的 Python 函数的例子是 len()
函数。
字符串
对于字符串,len()
返回字符数
元组
对于元组,len()
返回元组中的项数
字典
对于字典,len()
返回字典中键/值对的数量
类多态
多态经常用于类方法中,我们可以让多个类拥有相同名称的方法。
例如,假设我们有三个类: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") #创建 Car 类
boat1 = Boat("Ibiza", "Touring 20") #创建 Boat 类
plane1 = Plane("Boeing", "747") #创建 Plane 类
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()
方法。
由于多态,我们可以对所有类执行相同的方法。