This repository was archived by the owner on Jun 4, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo2_polymorphism.py
More file actions
58 lines (40 loc) · 1.55 KB
/
demo2_polymorphism.py
File metadata and controls
58 lines (40 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
demo2: 多态 (Polymorphism)
场景:支付系统——不同支付方式,同一个接口
"""
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount: float) -> str:
pass
@abstractmethod
def get_name(self) -> str:
pass
class WeChatPay(Payment):
def pay(self, amount: float) -> str:
return f"微信支付: {amount:.2f} (从零钱扣款)"
def get_name(self) -> str:
return "微信支付"
class Alipay(Payment):
def pay(self, amount: float) -> str:
return f"支付宝: {amount:.2f} (从余额扣款)"
def get_name(self) -> str:
return "支付宝"
class CreditCard(Payment):
def __init__(self, card_number: str):
self.card_number = card_number[-4:]
def pay(self, amount: float) -> str:
return f"信用卡(尾号{self.card_number}): {amount:.2f} (已授权)"
def get_name(self) -> str:
return f"信用卡({self.card_number})"
def process_payment(payment: Payment, amount: float):
print(f"[{payment.get_name()}] {payment.pay(amount)}")
if __name__ == "__main__":
print("=== 多态演示: 支付系统 ===\n")
payments = [WeChatPay(), Alipay(), CreditCard("6222021234567890")]
for p in payments:
process_payment(p, 99.50)
print(f"\n--- 多态的好处 ---")
print("1. 新增支付方式只需继承Payment, 不用改process_payment")
print("2. 所有支付方式遵循同一个接口")
print("3. 可以用列表统一管理不同类型的对象")