Python多态特性实现案例
多态是面向对象编程的重要特性,允许不同类的对象对同一方法做出不同响应,以下是几个典型的多态实现案例:

基本的多态实现(通过继承)
class Animal:
def speak(self):
raise NotImplementedError("子类必须实现这个方法")
class Dog(Animal):
def speak(self):
return "汪汪汪"
class Cat(Animal):
def speak(self):
return "喵喵喵"
class Duck(Animal):
def speak(self):
return "嘎嘎嘎"
# 多态的使用
def animal_sound(animal):
"""传入不同的动物对象,调用相同的speak方法"""
return animal.speak()
# 测试多态
animals = [Dog(), Cat(), Duck()]
for animal in animals:
print(f"{animal.__class__.__name__}: {animal_sound(animal)}")
鸭子类型(Duck Typing)实现多态
class Bird:
def fly(self):
return "鸟儿在飞"
class Airplane:
def fly(self):
return "飞机在飞"
class Superman:
def fly(self):
return "超人在飞"
# 多态函数 - 不关心对象类型,只关心是否有fly方法
def make_it_fly(flying_object):
return flying_object.fly()
# 测试鸭子类型多态
objects = [Bird(), Airplane(), Superman()]
for obj in objects:
print(f"{obj.__class__.__name__}: {make_it_fly(obj)}")
使用抽象基类(ABC)实现多态
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# 多态计算
def calculate_shape_info(shape):
return f"面积: {shape.area()}, 周长: {shape.perimeter()}"
# 测试
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(f"{shape.__class__.__name__}: {calculate_shape_info(shape)}")
运算符重载实现多态
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
"""重载+运算符,实现向量加法"""
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
elif isinstance(other, (int, float)):
return Vector(self.x + other, self.y + other)
else:
raise TypeError("不支持的类型")
def __str__(self):
return f"Vector({self.x}, {self.y})"
# 测试运算符多态
v1 = Vector(1, 2)
v2 = Vector(3, 4)
# 向量加向量
result1 = v1 + v2
print(f"向量相加: {result1}")
# 向量加数字
result2 = v1 + 10
print(f"向量加数字: {result2}")
实际应用案例 - 支付系统
class PaymentSystem:
def pay(self, amount):
raise NotImplementedError
class Alipay(PaymentSystem):
def pay(self, amount):
return f"使用支付宝支付 {amount} 元"
class WeChatPay(PaymentSystem):
def pay(self, amount):
return f"使用微信支付 {amount} 元"
class BankCard(PaymentSystem):
def pay(self, amount):
return f"使用银行卡支付 {amount} 元"
# 多态处理支付
def process_payment(payment_method, amount):
"""
统一的支付处理函数
任何实现了pay方法的对象都可以传入
"""
result = payment_method.pay(amount)
return f"【支付成功】{result}"
# 测试
payments = [Alipay(), WeChatPay(), BankCard()]
for payment in payments:
print(process_payment(payment, 100))
使用函数参数多态
def calculate_area(shape, *args):
"""
根据传入的不同形状计算面积
这是函数级别的多态
"""
if shape == "circle":
radius = args[0]
return 3.14 * radius ** 2
elif shape == "rectangle":
width, height = args
return width * height
elif shape == "triangle":
base, height = args
return 0.5 * base * height
else:
return None
# 测试
print(f"圆面积: {calculate_area('circle', 5)}")
print(f"矩形面积: {calculate_area('rectangle', 4, 6)}")
print(f"三角形面积: {calculate_area('triangle', 3, 8)}")
Python实现多态的几种方式:
- 继承+方法重写:最经典的多态实现方式
- 鸭子类型:Python特有的动态多态,不检查类型,只检查方法是否存在
- 抽象基类:强制规范接口,确保子类实现特定方法
- 运算符重载:让自定义类支持Python的内置运算符
- 函数重载:通过可变参数实现类似函数重载的效果
Python的多态核心思想是:"不关心对象是什么类型,只关心对象能做什么"。