Python 面向对象实战:在线支付系统的面向对象开发
在线支付系统的面向对象设计与实现
设计一个在线支付系统,我们需要考虑几个核心对象:用户、账户、支付方式、交易记录以及支付系统本身。下面是一个完整的实现方案,体现了面向对象的封装、继承和多态特性。
Python在线支付系统的面向对象实现
from datetime import datetime
import uuid
class InsufficientFundsError(Exception):
"""当账户余额不足时抛出的异常"""
pass
class InvalidPaymentMethodError(Exception):
"""当支付方式无效时抛出的异常"""
pass
class User:
"""用户类,代表支付系统中的用户"""
def __init__(self, name, email):
self.user_id = str(uuid.uuid4())
self.name = name
self.email = email
self.accounts = [] # 用户可以有多个账户
self.transactions = [] # 用户的交易记录
def add_account(self, account):
"""为用户添加账户"""
self.accounts.append(account)
account.set_user(self)
def view_transactions(self):
"""查看用户的所有交易记录"""
return self.transactions
def __str__(self):
return f"User: {self.name} (ID: {self.user_id})"
class Account:
"""账户类,代表用户的支付账户"""
def __init__(self, account_type):
self.account_id = str(uuid.uuid4())
self.account_type = account_type # 例如: "checking", "savings", "credit"
self.balance = 0.0
self.user = None # 关联的用户
def set_user(self, user):
"""设置账户关联的用户"""
self.user = user
def deposit(self, amount):
"""存款到账户"""
if amount > 0:
self.balance += amount
return True
return False
def withdraw(self, amount):
"""从账户取款"""
if amount > 0 and self.balance >= amount:
self.balance -= amount
return True
raise InsufficientFundsError(f"Insufficient funds for withdrawal of {amount}")
def get_balance(self):
"""获取账户余额"""
return self.balance
def __str__(self):
return f"{self.account_type.capitalize()} Account (ID: {self.account_id}) - Balance: ${self.balance:.2f}"
class PaymentMethod:
"""支付方式基类,所有支付方式都继承自此类"""
def __init__(self, account):
self.method_id = str(uuid.uuid4())
self.account = account # 关联的账户
self.is_active = True
def is_valid(self):
"""检查支付方式是否有效"""
return self.is_active and self.account is not None
def process_payment(self, amount):
"""处理支付,由子类实现具体逻辑"""
raise NotImplementedError("Subclasses must implement process_payment method")
def deactivate(self):
"""停用支付方式"""
self.is_active = False
class CreditCard(PaymentMethod):
"""信用卡支付方式"""
def __init__(self, account, card_number, expiry_date, cvv):
super().__init__(account)
self.card_number = card_number
self.expiry_date = expiry_date
self.cvv = cvv
def process_payment(self, amount):
if not self.is_valid():
raise InvalidPaymentMethodError("Credit card is invalid or inactive")
try:
# 对于信用卡,我们只是记录消费,不立即扣减(简化实现)
return True
except Exception as e:
print(f"Payment failed: {str(e)}")
return False
def __str__(self):
# 只显示卡号后4位,保护隐私
return f"Credit Card (****-****-****-{self.card_number[-4:]})"
class BankTransfer(PaymentMethod):
"""银行转账支付方式"""
def __init__(self, account, bank_name, routing_number):
super().__init__(account)
self.bank_name = bank_name
self.routing_number = routing_number
def process_payment(self, amount):
if not self.is_valid():
raise InvalidPaymentMethodError("Bank transfer method is invalid or inactive")
try:
# 银行转账直接从账户扣减金额
self.account.withdraw(amount)
return True
except InsufficientFundsError:
raise
except Exception as e:
print(f"Bank transfer failed: {str(e)}")
return False
def __str__(self):
return f"Bank Transfer ({self.bank_name})"
class Transaction:
"""交易记录类,记录每一笔支付交易"""
def __init__(self, user, payment_method, amount, description=""):
self.transaction_id = str(uuid.uuid4())
self.user = user
self.payment_method = payment_method
self.amount = amount
self.description = description
self.timestamp = datetime.now()
self.status = "pending" # pending, completed, failed
def complete(self):
"""标记交易为完成"""
self.status = "completed"
def fail(self):
"""标记交易为失败"""
self.status = "failed"
def __str__(self):
return f"Transaction {self.transaction_id}: ${self.amount:.2f} via {self.payment_method} - {self.status} at {self.timestamp.strftime('%Y-%m-%d %H:%M')}"
class PaymentSystem:
"""支付系统类,协调所有支付相关操作"""
def __init__(self, name):
self.name = name
self.users = []
def register_user(self, name, email):
"""注册新用户"""
user = User(name, email)
self.users.append(user)
return user
def create_account(self, user, account_type):
"""为用户创建新账户"""
account = Account(account_type)
user.add_account(account)
return account
def process_transaction(self, user, payment_method, amount, description=""):
"""处理支付交易"""
if amount <= 0:
raise ValueError("Payment amount must be positive")
# 创建交易记录
transaction = Transaction(user, payment_method, amount, description)
try:
# 处理支付
success = payment_method.process_payment(amount)
if success:
transaction.complete()
print(f"Payment successful: ${amount:.2f}")
else:
transaction.fail()
print("Payment failed")
except (InsufficientFundsError, InvalidPaymentMethodError) as e:
transaction.fail()
print(f"Payment failed: {str(e)}")
except Exception as e:
transaction.fail()
print(f"An error occurred: {str(e)}")
# 记录交易
user.transactions.append(transaction)
return transaction
def get_user_transactions(self, user):
"""获取用户的所有交易"""
return user.view_transactions()
def __str__(self):
return f"Payment System: {self.name} (Users: {len(self.users)})"
# 演示使用
if __name__ == "__main__":
# 创建支付系统
payment_system = PaymentSystem("SecurePay")
# 注册用户
alice = payment_system.register_user("Alice Smith", "alice@example.com")
print(alice)
# 为用户创建账户
checking_account = payment_system.create_account(alice, "checking")
checking_account.deposit(1000.0)
print(checking_account)
# 创建支付方式
credit_card = CreditCard(checking_account, "4111111111111111", "12/25", "123")
bank_transfer = BankTransfer(checking_account, "National Bank", "123456789")
# 处理交易
print("\nProcessing first transaction...")
transaction1 = payment_system.process_transaction(
alice,
bank_transfer,
250.50,
"Grocery shopping"
)
print(checking_account) # 显示扣款后的余额
print("\nProcessing second transaction...")
transaction2 = payment_system.process_transaction(
alice,
credit_card,
150.00,
"Clothing purchase"
)
print(checking_account) # 信用卡交易不影响余额(简化实现)
print("\nProcessing a large transaction...")
try:
transaction3 = payment_system.process_transaction(
alice,
bank_transfer,
1000.00,
"Attempting to withdraw too much"
)
except Exception as e:
pass
print(checking_account)
# 查看交易历史
print("\nTransaction history:")
for tx in payment_system.get_user_transactions(alice):
print(tx)
创建时间:00:30
系统设计说明
这个在线支付系统包含以下核心组件:
-
异常类:定义了支付过程中可能出现的异常,如余额不足、支付方式无效等
-
User 类:代表系统用户,包含用户基本信息和关联的账户、交易记录
-
Account 类:用户的账户,支持存款、取款等基本操作
-
PaymentMethod 类:支付方式基类,以及两个具体实现(CreditCard 和 BankTransfer),展示了继承和多态的应用
-
Transaction 类:记录每一笔交易的详细信息,包括金额、时间、状态等
-
PaymentSystem 类:支付系统核心,协调用户注册、账户管理和交易处理
系统特点
- 封装性:每个类都封装了自身的数据和操作方法,对外提供清晰的接口
- 继承性:CreditCard 和 BankTransfer 继承自 PaymentMethod 基类
- 多态性:不同支付方式实现了相同的 process_payment 方法,但有不同的行为
- 可扩展性:可以很容易地添加新的支付方式(如 PayPal、加密货币等)
- 异常处理:对支付过程中可能出现的错误进行了处理
运行示例代码可以看到整个支付流程的模拟,包括用户注册、账户创建、存款、不同方式的支付以及交易历史查询等功能。
更多推荐

所有评论(0)