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

调用Deposit()和Withdraw()方法时为何出现UnboundLocalError?

解决UnboundLocalError及代码逻辑修复

错误原因分析

  • 局部变量未定义:在Withdraw()和Deposit()方法中,直接使用balance -= amount或balance += amount时,Python会将balance视为局部变量,但方法内并未提前定义它,因此抛出UnboundLocalError。即使类里定义了balance = 0,不通过类或实例引用的话,方法内无法直接访问类变量。
  • 方法定义错误:所有类方法都没有添加self(实例方法)或cls(类方法)参数,导致无法正确访问类或实例的属性。
  • 列表操作错误:Customer.CreateNewAccount中使用Customer.accounts += AccountName会将字符串拆分为单个字符添加到列表,应该用append()添加完整的账户实例。
  • 拼写错误:Deposit()方法里的输入提示和递归调用都写错了deposit(写成了depsoit)。
  • 设计逻辑问题:用类变量balance会导致所有账户共享同一个余额,不符合实际业务逻辑,应该每个账户实例拥有独立的余额。

修复后的完整代码

class Customer:
    accounts = []

    def __init__(self, name, pin):
        self.name = name
        self.pin = pin
        self.account = Account()  # 每个客户对应一个账户实例

    @classmethod
    def GetNewAccountInfo(cls):
        name = input("Enter Account Name: ")
        pin = input("Enter Account Pin: ")
        # 创建客户实例并添加到账户列表
        new_customer = Customer(name, pin)
        cls.accounts.append(new_customer)
        # 进入该客户的账户操作窗口
        new_customer.account.MainWindow(new_customer)

class Account:
    def __init__(self):
        self.balance = 0  # 每个账户实例独立的余额

    def Withdraw(self):
        while True:
            try:
                amount = int(input("Enter the amount you wish to withdraw: "))
                if amount <= 0:
                    print("You cannot withdraw a negative or zero amount.")
                elif amount > self.balance:
                    print("Insufficient balance.")
                else:
                    self.balance -= amount
                    print(f"Withdrawal successful. Current balance: {self.balance}")
                    break
            except ValueError:
                print("Please enter a valid number.")
        self.MainWindow(self.customer)

    def Deposit(self):
        while True:
            try:
                amount = int(input("Enter the amount you wish to deposit: "))
                if amount <= 0:
                    print("You cannot deposit a negative or zero amount.")
                else:
                    self.balance += amount
                    print(f"Deposit successful. Current balance: {self.balance}")
                    break
            except ValueError:
                print("Please enter a valid number.")
        self.MainWindow(self.customer)

    def CheckBalance(self):
        print(f"Current account balance: {self.balance}")
        self.MainWindow(self.customer)

    def MainWindow(self, customer):
        self.customer = customer
        while True:
            print(f"\nWelcome, {customer.name}!")
            try:
                selection = int(input("1. Withdraw \n2. Deposit \n3. Check Balance \n4. Exit \nEnter your selection: "))
                if selection == 1:
                    self.Withdraw()
                elif selection == 2:
                    self.Deposit()
                elif selection == 3:
                    self.CheckBalance()
                elif selection == 4:
                    print("Thank you for using our service.")
                    break
                else:
                    print("Enter a valid selection (1-4).")
            except ValueError:
                print("Please enter a valid integer.")

# 启动程序
Customer.GetNewAccountInfo()

主要修改说明

  1. 实例化账户余额:将Account的balance从类变量改为实例变量(self.balance = 0),每个账户拥有独立余额。
  2. 修正方法参数:所有类方法添加self参数(实例方法),Customer.GetNewAccountInfo改为类方法(@classmethod),确保能正确访问类/实例属性。
  3. 修复列表操作:Customer.accounts存储Customer实例,用append()添加,避免字符串拆分问题。
  4. 替换递归为循环:将错误输入后的递归调用改为while循环,避免栈溢出风险。
  5. 修复拼写错误:修正depsoit为deposit。
  6. 优化交互逻辑:添加余额不足判断、输入类型校验,退出选项改为真正退出程序,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:29:57