多态技术
理解多态性
多态性允许不同类型的对象被统一对待,从而实现更灵活和可扩展的代码设计。
Python 中的多态类型
1. 方法重写
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
def animal_sound(animal):
animal.speak()
## 多态行为
dog = Dog()
cat = Cat()
animal_sound(dog) ## 输出: Dog barks
animal_sound(cat) ## 输出: Cat meows
2. 鸭子类型
class Duck:
def swim(self):
print("Duck swimming")
def fly(self):
print("Duck flying")
class Airplane:
def fly(self):
print("Airplane flying")
def perform_fly(entity):
entity.fly()
## 实际的鸭子类型
duck = Duck()
airplane = Airplane()
perform_fly(duck) ## 可行
perform_fly(airplane) ## 可行
多态可视化
classDiagram
Animal <|-- Dog
Animal <|-- Cat
Animal : +speak()
Dog : +speak()
Cat : +speak()
多态技术比较
技术 |
描述 |
优点 |
局限性 |
方法重写 |
在子类中重新定义方法 |
行为灵活 |
需要继承 |
鸭子类型 |
关注对象能力 |
动态且灵活 |
类型安全性较低 |
抽象基类 |
定义接口契约 |
强类型检查 |
实现更复杂 |
高级多态模式
带有多态性的抽象基类
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def print_area(shape):
print(f"Area: {shape.area()}")
## 多态使用
circle = Circle(5)
rectangle = Rectangle(4, 6)
print_area(circle) ## 输出: Area: 78.5
print_area(rectangle) ## 输出: Area: 24
带有混入类的多态性
class LoggerMixin:
def log(self, message):
print(f"[LOG] {message}")
class DatabaseHandler(LoggerMixin):
def save(self, data):
self.log("Saving data")
## 实际保存逻辑
class FileHandler(LoggerMixin):
def save(self, data):
self.log("Saving file")
## 实际文件保存逻辑
LabEx 实际示例
class PaymentProcessor:
def process_payment(self, amount):
raise NotImplementedError("Subclass must implement abstract method")
class CreditCardProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"Processing credit card payment: ${amount}")
class PayPalProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"Processing PayPal payment: ${amount}")
def make_payment(processor, amount):
processor.process_payment(amount)
## 多态支付处理
credit_card = CreditCardProcessor()
paypal = PayPalProcessor()
make_payment(credit_card, 100)
make_payment(paypal, 50)
最佳实践
- 使用多态性创建更灵活的设计
- 优先使用组合而非复杂的继承
- 为清晰的接口实现抽象基类
- 利用鸭子类型实现动态行为
- 保持多态实现简单明了
性能考虑
- 多态可能会引入轻微的性能开销
- 方法解析和动态调度的影响最小
- 关注代码的可读性和可维护性
多态性为在 Python 中创建灵活且可扩展的面向对象设计提供了强大的技术,实现了更动态和适应性更强的代码结构。