本文目录导读:

我来通过多个案例详细说明Python中多态特性的实现方式。
基础多态示例 - 方法重写
class Animal:
def speak(self):
pass
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):
return animal.speak()
# 使用示例
animals = [Dog(), Cat(), Duck()]
for animal in animals:
print(f"{animal.__class__.__name__}: {animal_speak(animal)}")
使用抽象基类实现多态
from abc import ABC, abstractmethod
import math
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 math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * 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)
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
# 使用海伦公式
s = self.perimeter() / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c
# 多态函数
def print_shape_info(shape):
print(f"面积: {shape.area():.2f}")
print(f"周长: {shape.perimeter():.2f}")
# 使用示例
shapes = [
Circle(5),
Rectangle(4, 6),
Triangle(3, 4, 5)
]
for shape in shapes:
print(f"\n{shape.__class__.__name__}:")
print_shape_info(shape)
鸭子类型实现多态
# Python的鸭子类型:只要像鸭子一样走路,就是鸭子
class AudioPlayer:
def play(self):
return "播放音频..."
class VideoPlayer:
def play(self):
return "播放视频..."
class GamePlayer:
def play(self):
return "运行游戏..."
class MediaController:
def __init__(self, player):
self.player = player
def play_media(self):
return self.player.play()
# 使用示例
players = [AudioPlayer(), VideoPlayer(), GamePlayer()]
controller = MediaController(None)
for player in players:
controller.player = player
print(controller.play_media())
运算符重载实现多态
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 __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __str__(self):
return f"Vector({self.x}, {self.y})"
# 使用示例
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(f"v1 + v2 = {v1 + v2}")
print(f"v1 + 5 = {v1 + 5}")
print(f"v1 * 3 = {v1 * 3}")
实际应用案例 - 支付系统
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass
@abstractmethod
def refund(self, amount):
pass
class CreditCardPayment(Payment):
def __init__(self, card_number, cvv):
self.card_number = card_number
self.cvv = cvv
def pay(self, amount):
return f"信用卡支付 {amount} 元,卡号: {self.card_number[-4:]}"
def refund(self, amount):
return f"信用卡退款 {amount} 元到卡号: {self.card_number[-4:]}"
class WeChatPayment(Payment):
def __init__(self, open_id):
self.open_id = open_id
def pay(self, amount):
return f"微信支付 {amount} 元,用户ID: {self.open_id}"
def refund(self, amount):
return f"微信退款 {amount} 元到用户ID: {self.open_id}"
class AlipayPayment(Payment):
def __init__(self, user_id):
self.user_id = user_id
def pay(self, amount):
return f"支付宝支付 {amount} 元,用户ID: {self.user_id}"
def refund(self, amount):
return f"支付宝退款 {amount} 元到用户ID: {self.user_id}"
class PaymentProcessor:
def process_payment(self, payment_method, amount, action="pay"):
if action == "pay":
return payment_method.pay(amount)
elif action == "refund":
return payment_method.refund(amount)
# 使用示例
processor = PaymentProcessor()
payments = [
CreditCardPayment("1234567890123456", "123"),
WeChatPayment("wx_user_001"),
AlipayPayment("alipay_user_001")
]
for payment in payments:
print(processor.process_payment(payment, 100, "pay"))
print(processor.process_payment(payment, 50, "refund"))
print("-" * 40)
协议和混入类实现多态
class FlyableMixin:
def fly(self):
return f"{self.name} 正在飞行中..."
class SwimmableMixin:
def swim(self):
return f"{self.name} 正在游泳中..."
class Bird(FlyableMixin):
def __init__(self, name):
self.name = name
def move(self):
return self.fly()
class Fish(SwimmableMixin):
def __init__(self, name):
self.name = name
def move(self):
return self.swim()
class Duck(FlyableMixin, SwimmableMixin):
def __init__(self, name):
self.name = name
def move(self):
return f"{self.name} 既能飞也能游:{self.fly()},{self.swim()}"
# 多态函数
def make_move(creature):
return creature.move()
# 使用示例
creatures = [
Bird("老鹰"),
Fish("金鱼"),
Duck("唐老鸭")
]
for creature in creatures:
print(make_move(creature))
使用函数作为参数实现多态
from typing import Callable, List
class Calculator:
def __init__(self, operation: Callable):
self.operation = operation
def calculate(self, a, b):
return self.operation(a, b)
# 不同的操作函数
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
return "不能除以零"
# 高阶函数应用
def apply_operations(x: float, y: float, operations: List[Callable]):
results = []
for op in operations:
results.append(op(x, y))
return results
# 使用示例
operations = [add, subtract, multiply, divide]
calculators = [Calculator(op) for op in operations]
a, b = 10, 3
print(f"计算结果 ({a}, {b}):")
for calc in calculators:
print(calc.calculate(a, b))
# 使用高阶函数
print("\n批量计算:")
results = apply_operations(a, b, operations)
for op, result in zip(["add", "subtract", "multiply", "divide"], results):
print(f"{op}: {result}")
- 继承实现多态:通过继承抽象基类,子类实现不同的方法
- 鸭子类型:Python天然支持,只要对象有相同的方法签名即可
- 运算符重载:通过特殊方法实现不同对象类型的操作
- 组合与接口:使用抽象基类(ABC)定义协议
- 函数式多态:通过传递不同的函数作为参数
多态的核心优势:
- 提高代码复用性
- 增强程序扩展性
- 实现松耦合设计
- 支持开闭原则
通过这些案例,你可以看到Python实现多态的多种方式,根据具体场景选择最适合的实现方法。