Python实例题:面向对象的银行系统

目录

Python实例题

题目

要求:

解题思路:

代码实现:

Python实例题

题目

面向对象的银行系统

要求

  • 设计一个银行系统,包含 User(用户)、Account(账户)、SavingsAccount(储蓄账户)、CheckingAccount(支票账户)和 Bank(银行)类。
  • User 类:存储用户信息(姓名、身份证号、手机号),可以关联多个账户。
  • Account 类:基础账户类,包含账户号、余额、开户日期,支持存款、取款、查询余额操作。
  • SavingsAccount 类:继承自 Account,支持利息计算(年利率 2%)。
  • CheckingAccount 类:继承自 Account,支持透支功能(透支限额 1000 元)。
  • Bank 类:管理所有用户和账户,支持用户开户、账户间转账、显示所有用户信息等操作。
  • 添加适当的异常处理(如余额不足、账户不存在等)。

解题思路

  • 使用继承和多态实现不同类型的账户。
  • 使用字典存储用户和账户信息。
  • 实现账户操作的业务逻辑和验证。

代码实现

from datetime import datetime
import uuid

class User:
    def __init__(self, name, id_card, phone):
        self.name = name
        self.id_card = id_card
        self.phone = phone
        self.accounts = []
    
    def add_account(self, account):
        self.accounts.append(account)
    
    def get_accounts_info(self):
        return [f"{account.account_type}: {account.account_number} (余额: {account.balance})" 
                for account in self.accounts]

class Account:
    def __init__(self, account_type):
        self.account_number = str(uuid.uuid4())[:8]  # 简化的账户号
        self.balance = 0
        self.account_type = account_type
        self.create_date = datetime.now()
    
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("存款金额必须大于0")
        self.balance += amount
        return True
    
    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("取款金额必须大于0")
        if amount > self.balance:
            raise ValueError("余额不足")
        self.balance -= amount
        return True
    
    def get_balance(self):
        return self.balance

class SavingsAccount(Account):
    def __init__(self):
        super().__init__("储蓄账户")
        self.annual_interest_rate = 0.02  # 2%年利率
    
    def calculate_interest(self, months):
        """计算指定月数的利息"""
        if months <= 0:
            raise ValueError("月数必须大于0")
        return self.balance * (self.annual_interest_rate / 12) * months

class CheckingAccount(Account):
    def __init__(self):
        super().__init__("支票账户")
        self.overdraft_limit = 1000  # 透支限额
    
    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("取款金额必须大于0")
        if amount > (self.balance + self.overdraft_limit):
            raise ValueError("超出透支限额")
        self.balance -= amount
        return True

class Bank:
    def __init__(self, name):
        self.name = name
        self.users = {}  # ID卡 -> User
        self.accounts = {}  # 账户号 -> Account
    
    def create_user(self, name, id_card, phone):
        if id_card in self.users:
            raise ValueError("该身份证号已存在")
        user = User(name, id_card, phone)
        self.users[id_card] = user
        return user
    
    def create_account(self, id_card, account_type):
        if id_card not in self.users:
            raise ValueError("用户不存在")
        
        user = self.users[id_card]
        if account_type == "savings":
            account = SavingsAccount()
        elif account_type == "checking":
            account = CheckingAccount()
        else:
            raise ValueError("无效的账户类型")
        
        user.add_account(account)
        self.accounts[account.account_number] = account
        return account
    
    def transfer(self, from_account, to_account, amount):
        if from_account not in self.accounts:
            raise ValueError("转出账户不存在")
        if to_account not in self.accounts:
            raise ValueError("转入账户不存在")
        
        source = self.accounts[from_account]
        target = self.accounts[to_account]
        
        # 检查余额
        source.withdraw(amount)  # 可能抛出余额不足异常
        target.deposit(amount)
        return True
    
    def get_user_info(self, id_card):
        if id_card not in self.users:
            raise ValueError("用户不存在")
        user = self.users[id_card]
        return {
            "name": user.name,
            "id_card": user.id_card,
            "phone": user.phone,
            "accounts": user.get_accounts_info()
        }

# 示例使用
if __name__ == "__main__":
    bank = Bank("示例银行")
    
    # 创建用户
    user1 = bank.create_user("张三", "1234567890", "13800138000")
    user2 = bank.create_user("李四", "0987654321", "13900139000")
    
    # 为用户创建账户
    savings_acc1 = bank.create_account("1234567890", "savings")
    checking_acc1 = bank.create_account("1234567890", "checking")
    savings_acc2 = bank.create_account("0987654321", "savings")
    
    # 存款
    savings_acc1.deposit(5000)
    checking_acc1.deposit(2000)
    
    # 转账
    try:
        bank.transfer(savings_acc1.account_number, savings_acc2.account_number, 1000)
        print("转账成功")
    except ValueError as e:
        print(f"转账失败: {e}")
    
    # 透支测试
    try:
        checking_acc1.withdraw(3000)  # 允许透支1000
        print("透支成功")
    except ValueError as e:
        print(f"透支失败: {e}")
    
    # 计算利息
    interest = savings_acc1.calculate_interest(6)  # 6个月利息
    print(f"储蓄账户利息: {interest:.2f}")
    
    # 显示用户信息
    print("\n用户信息:")
    for id_card in bank.users:
        info = bank.get_user_info(id_card)
        print(f"{info['name']} (ID: {info['id_card']}):")
        for acc in info['accounts']:
            print(f"  - {acc}")

你可能感兴趣的:(实例,python,开发语言)