从实际问题出发学习Python的面向对象编程:案例解析

原创 阳光穿透心脏的1/2处 2025-03-11 00:48 10阅读 0赞

面向对象编程(Object-Oriented Programming,简称OOP)是Python等现代编程语言的重要特性之一。下面我们将通过一个实际问题来解析如何在Python中使用面向对象编程。

案例:一款银行应用

  1. 定义

    • 银行账户(Account)
    • 存款操作(DepositOperation)
    • 取款操作(WithdrawalOperation)
  2. 实现

  1. # 定义账户类
  2. class Account:
  3. def __init__(self, account_number, balance=0):
  4. self.account_number = account_number
  5. self.balance = balance
  6. # 存取款方法
  7. def deposit(self, amount):
  8. self.balance += amount
  9. print(f"存款成功,金额:{amount}, 新余额:{self.balance}}")
  10. def withdrawal(self, amount):
  11. if amount > self.balance:
  12. print("取款失败,余额不足")
  13. else:
  14. self.balance -= amount
  15. print(f"取款成功,金额:{amount}, 新余额:{self.balance}}")
  16. # 定义存款操作类
  17. class DepositOperation:
  18. def __init__(self, account):
  19. self.account = account
  20. # 执行存款操作
  21. def execute(self, amount):
  22. self.account.deposit(amount)
  23. return f"存款成功,金额:{amount}"
  24. # 定义取款操作类
  25. class WithdrawalOperation:
  26. def __init__(self, account, amount=0):
  27. self.account = account
  28. self.amount = amount
  29. # 执行取款操作
  30. def execute(self):
  31. if self.amount > self.account.balance:
  32. return f"取款失败,余额不足"
  33. else:
  34. self.account.withdrawal(self.amount)
  35. return f"取款成功,金额:{self.amount}"
  36. # 使用示例
  37. account1 = Account("0001")
  38. account2 = Account("0002", 500)
  39. deposit_op1 = DepositOperation(account1, 200))
  40. deposit_op2 = DepositOperation(account2, 300))
  41. withdrawal_op1 = WithdrawalOperation(account1, 100))
  42. withdrawal_op2 = WithdrawalOperation(account2, 50), 50)
  43. print(deposit_op1.execute())
  44. print(deposit_op2.execute())
  45. print(withdrawal_op1.execute())
  46. print(withdrawal_op2.execute())

通过这个例子,你可以看到如何定义具有特定行为的类(如存款账户、取款操作等),以及如何在实际问题中使用这些类进行交互。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,10人围观)

还没有评论,来说两句吧...

相关阅读