第 37 课 · 阶段六 · 面向对象
面向对象综合案例
把前几课面向对象知识串起来,做一个完整的银行账户系统:存款、取款、转账、利息,体验真实项目的类设计。
🎯 学完本课你将掌握
- 综合运用类、继承、魔术方法设计系统
- 理解数据校验与安全边界
- 体验从需求到代码的完整过程
一、需求分析
做一个银行账户系统,要求:账户有卡号、户名、余额;支持存款、取款、查询余额、转账;取款不能透支;每天有操作记录。
二、设计 Account 类
account.py
1class Account:2 def __init__(self, name, balance=0):3 self.name = name4 self.balance = balance5 self.records = [] # 交易记录67 def deposit(self, amount):8 if amount <= 0:9 raise ValueError("存款金额必须大于0")10 self.balance += amount11 self.records.append(f"存入 {amount}")1213 def withdraw(self, amount):14 if amount <= 0:15 raise ValueError("取款金额必须大于0")16 if amount > self.balance:17 raise ValueError("余额不足")18 self.balance -= amount19 self.records.append(f"取出 {amount}")2021 def transfer(self, other, amount):22 self.withdraw(amount)23 other.deposit(amount)24 self.records.append(f"转账 {amount} 给 {other.name}")2526 def __str__(self):27 return f"{self.name}的账户,余额:{self.balance:.2f}"2829 def __lt__(self, other):30 return self.balance < other.balance三、运行测试
main.py
1from account import Account23a = Account("小明", 1000)4b = Account("小红", 500)56a.deposit(300)7a.withdraw(200)8a.transfer(b, 400)910print(a) # 小明 余额:700.0011print(b) # 小红 余额:900.0012print("交易记录:")13for r in a.records:14 print("-", r)1516try:17 a.withdraw(100000)18except ValueError as e:19 print("取款失败:", e)四、继承扩展:利息账户
savings.py
1from account import Account23class SavingsAccount(Account):4 """带利息的账户"""5 RATE = 0.03 # 年利率 3%67 def add_interest(self):8 interest = self.balance * self.RATE9 self.balance += interest10 self.records.append(f"获得利息 {interest:.2f}")11 return interest1213s = SavingsAccount("小刚", 1000)14s.add_interest()15print(s) # 小刚 余额:1030.00五、多态应用:批量操作
多态演示.py
1from account import Account2from savings import SavingsAccount34accounts = [Account("小明", 1000), SavingsAccount("小刚", 1000)]5# 不同类型的账户可以统一循环处理(多态)6for acc in accounts:7 acc.deposit(100)8 print(acc)六、工程小技巧
- 校验数据:负数、超支都要在方法里拦截,抛出 ValueError。
- 封装细节:余额只能通过方法修改,外部不能随便改。
- 记录留痕:每次操作写入 records,方便追溯。
- 用 __str__/__lt__ 让对象打印友好、可排序。
七、常见错误与解决
常见错误与解决
| 错误现象 | 原因 / 解决方法 |
|---|---|
能取出负数或超支 | 方法内没做校验,参考 withdraw 里的两次 if 判断。 |
不同文件互相导入失败 | 确认文件在同一目录,用 from account import Account 正确导入。 |
余额被外部直接改坏 | 用“私有化”惯例:属性名前加下划线 _balance,并只提供方法访问。 |
✍️ 小练习
给账户系统增加:查看历史记录的 show_records() 方法、用 __lt__ 找出余额最多的账户、再写一个固定利率的 VIP 账户类。
📌 本节小结
综合项目检验面向对象:数据校验、封装、继承、多态、魔术方法全部用上。能独立设计这个系统,说明面向对象你已经真正上手,下一阶段进入进阶主题。