You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python ATM代码优化:实现存款后查询余额显示更新值

问题分析

核心问题出在两处:

  • ATM类的user_bank_balance方法每次调用时,都会把self.user_balance重新赋值为300,完全忽略之前的存款操作
  • 存款操作计算的新余额只存在临时变量total_savings里,没有同步更新到存储用户余额的user_balance属性上
简单修改方案

不用大幅重构代码,调整几个关键逻辑就能解决问题:

  1. 在ATM类的__init__方法里初始化用户初始余额,替代每次查询时的重置操作:
def __init__(self):
    self.machine_balance = self.atm_balance
    self.user_balance = 300  # 把初始余额移到这里初始化
  1. 修改user_bank_balance方法,直接打印已有的用户余额:
def user_bank_balance(self):
    print('Your current balance is ${}'.format(self.user_balance))
  1. 调整deposit_atm方法,直接更新user_balance,去掉多余的临时变量:
def deposit_atm(self, user):
    deposit_m = float(input('How much do you want to deposit? '))
    if deposit_m > user.deposit_money():
        print('You do not have enough money to deposit')
    else:
        print('Amount deposited: ${}'.format(deposit_m))
        self.user_balance += deposit_m  # 直接更新用户余额
    print('Total amount in your account: ${}'.format(self.user_balance))
  1. 修复withdraw_atm方法,基于user_balance计算并更新取款后的余额:
def withdraw_atm(self):
    sum_to_withdraw = float(input('How much do you want to withdraw? '))
    if self.machine_balance > sum_to_withdraw and self.user_balance > sum_to_withdraw:
        self.user_balance -= sum_to_withdraw  # 更新用户余额
        print("You have withdrawn {}".format(sum_to_withdraw))
        print('Your balance is {}'.format(self.user_balance))
    elif self.machine_balance > sum_to_withdraw and self.user_balance < sum_to_withdraw:
        print('Daily limit exceeded')
    else:
        print('ATM out of service')
修改后的完整代码
class User:

    def __init__(self):
        self.fname = input('Enter your first name: ')
        self.lname = input('Enter your last name: ')
        self.age = input('Enter your age: ')

    def user_details(self):
        print('Details:')
        print(f"First Name: {self.fname}")
        print(f"Last Name: {self.lname}")
        print(f"User age: {self.age}")

    def deposit_money(self):
        self.deposit_amount = 100
        return self.deposit_amount
    
    def withdraw_money(self, withdraw_amount):
        self.withdraw_amount = withdraw_amount
        return self.withdraw_amount
    
class ATM:
    
    atm_balance = 10000

    def __init__(self):
        self.machine_balance = self.atm_balance
        self.user_balance = 300  # 初始化用户初始余额
    
    def user_bank_balance(self):
        print ('Your current balance is ${}'.format(self.user_balance))  # 直接打印当前余额

    def deposit_atm(self, user):
        deposit_m = float(input('How much do you want to deposit? '))
        if deposit_m > user.deposit_money():
            print('You do not have enough money to deposit')
        else:
            print('Amount deposited: ${}'.format(deposit_m))
            self.user_balance += deposit_m  # 更新用户余额
        print('Total amount in your account: ${}'.format(self.user_balance))

    def withdraw_atm(self):
        sum_to_withdraw = float(input('How much do you want to withdraw? '))
        if self.machine_balance > sum_to_withdraw and self.user_balance > sum_to_withdraw:
            self.user_balance -= sum_to_withdraw  # 更新用户余额
            print("You have withdrawn {}".format(sum_to_withdraw))
            print('Your balance is {}'.format(self.user_balance))
        elif self.machine_balance > sum_to_withdraw and self.user_balance < sum_to_withdraw:
            print('Daily limit exceeded')
        else:
            print('ATM out of service')

class ATMUsage:
    @classmethod
    def run(cls):
        
        print('Bulbank ATM')
        print(""" 
        Type 'Balance' to check your current balance,
        Type  'Deposit' to deposit amount into your account,
        Type  'Withdraw' to withdraw from your account,
        Type  'Exit' to exit from your account,
            """)
        active = True
        user1 = User()
        atm1 = ATM()
        user1.user_details()
        while active:
            selection = input("What would you like to do: 'Balance', 'Deposit', 'Withdraw', 'Exit': ").lower()
            if selection == 'balance':
                atm1.user_bank_balance()
            elif selection == 'deposit':
                atm1.deposit_atm(user1)
            elif selection == "withdraw":
                atm1.withdraw_atm()
            elif selection == 'exit':
                print('Thanks for passing by. Have a good one!')
                break
            else:
                print('Wrong selection. Please, try again')

ATMUsage.run()
可选小优化(不增加复杂度)
  • 提前将输入的操作选项转为小写,避免重复调用.lower()
  • 修正了原代码中拼写错误eceeded为exceeded
  • 调整取款提示文本为符合语法的withdrawn

内容的提问来源于stack exchange,提问作者gginchev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:31:23