第 37 课 · 阶段六 · 面向对象

面向对象综合案例

把前几课面向对象知识串起来,做一个完整的银行账户系统:存款、取款、转账、利息,体验真实项目的类设计。

第 37 课阶段六 · 面向对象难度:进阶建议时长:45 分钟关键词:综合实战 · 银行账户 · 学生管理

🎯 学完本课你将掌握

  • 综合运用类、继承、魔术方法设计系统
  • 理解数据校验与安全边界
  • 体验从需求到代码的完整过程

一、需求分析

做一个银行账户系统,要求:账户有卡号、户名、余额;支持存款、取款、查询余额、转账;取款不能透支;每天有操作记录。

二、设计 Account 类

account.py
1class Account:
2 def __init__(self, name, balance=0):
3 self.name = name
4 self.balance = balance
5 self.records = [] # 交易记录
6
7 def deposit(self, amount):
8 if amount <= 0:
9 raise ValueError("存款金额必须大于0")
10 self.balance += amount
11 self.records.append(f"存入 {amount}")
12
13 def withdraw(self, amount):
14 if amount <= 0:
15 raise ValueError("取款金额必须大于0")
16 if amount > self.balance:
17 raise ValueError("余额不足")
18 self.balance -= amount
19 self.records.append(f"取出 {amount}")
20
21 def transfer(self, other, amount):
22 self.withdraw(amount)
23 other.deposit(amount)
24 self.records.append(f"转账 {amount} 给 {other.name}")
25
26 def __str__(self):
27 return f"{self.name}的账户,余额:{self.balance:.2f}"
28
29 def __lt__(self, other):
30 return self.balance < other.balance

三、运行测试

main.py
1from account import Account
2
3a = Account("小明", 1000)
4b = Account("小红", 500)
5
6a.deposit(300)
7a.withdraw(200)
8a.transfer(b, 400)
9
10print(a) # 小明 余额:700.00
11print(b) # 小红 余额:900.00
12print("交易记录:")
13for r in a.records:
14 print("-", r)
15
16try:
17 a.withdraw(100000)
18except ValueError as e:
19 print("取款失败:", e)

四、继承扩展:利息账户

savings.py
1from account import Account
2
3class SavingsAccount(Account):
4 """带利息的账户"""
5 RATE = 0.03 # 年利率 3%
6
7 def add_interest(self):
8 interest = self.balance * self.RATE
9 self.balance += interest
10 self.records.append(f"获得利息 {interest:.2f}")
11 return interest
12
13s = SavingsAccount("小刚", 1000)
14s.add_interest()
15print(s) # 小刚 余额:1030.00

五、多态应用:批量操作

多态演示.py
1from account import Account
2from savings import SavingsAccount
3
4accounts = [Account("小明", 1000), SavingsAccount("小刚", 1000)]
5# 不同类型的账户可以统一循环处理(多态)
6for acc in accounts:
7 acc.deposit(100)
8 print(acc)

六、工程小技巧

七、常见错误与解决

常见错误与解决

错误现象原因 / 解决方法
能取出负数或超支方法内没做校验,参考 withdraw 里的两次 if 判断。
不同文件互相导入失败确认文件在同一目录,用 from account import Account 正确导入。
余额被外部直接改坏用“私有化”惯例:属性名前加下划线 _balance,并只提供方法访问。
✍️ 小练习
给账户系统增加:查看历史记录的 show_records() 方法、用 __lt__ 找出余额最多的账户、再写一个固定利率的 VIP 账户类。
📌 本节小结
综合项目检验面向对象:数据校验、封装、继承、多态、魔术方法全部用上。能独立设计这个系统,说明面向对象你已经真正上手,下一阶段进入进阶主题。