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

Python类定义方式咨询及BankAccount实例化NameError报错排查

问题解答

定义Python类的其他方法

除了常规使用class关键字声明类的方式外,还有3种常见的类定义方式:

  • 用type()动态创建类:type是Python的内置元类,传入「类名、父类元组、类属性/方法字典」三个参数即可直接生成类,示例:
# 先定义类需要的方法
def __init__(self, balance, name):
    self.balance = balance
    self.name = name
    self.num_deposits = 0
    self.deposit_total = 0
    self.num_withdraws = 0
    self.withdraw_total = 0

def deposit(self, amount):
    self.balance += amount
    self.deposit_total += amount
    self.num_deposits += 1

# 直接用type生成类
BankAccount = type('BankAccount', (), {
    '__init__': __init__,
    'deposit': deposit
})
  • 用dataclasses.dataclass装饰器快速创建数据类:适合以存储数据为核心的轻量类,无需手动编写__init__方法:
from dataclasses import dataclass

@dataclass
class BankAccount:
    balance: int
    name: str
    num_deposits: int = 0
    deposit_total: int = 0
    num_withdraws: int = 0
    withdraw_total: int = 0
  • 自定义元类控制类创建:继承type实现自定义元类,可批量干预类的属性、方法定义逻辑,适合框架级的类行为定制场景。

代码报错及逻辑修复

核心报错原因

你遇到的NameError: name 'BankAccount'未定义是因为实例化类、调用方法的代码被写在了class BankAccount的内部缩进块中:Python解释器执行到内部的BankAccount1 = BankAccount(0 , "chase")时,BankAccount类的定义还没有完成,自然找不到对应的名称,需要把这部分代码移到类的外部。

其他需要修复的问题

  • 所有实例属性访问、实例方法调用都需要加self.前缀:直接写num_deposits会被识别为局部变量,无法跨方法共享,必须写成self.num_deposits
  • 方法名大小写不匹配:定义的存款方法是Deposit,调用时写的是小写开头的deposit,会报方法不存在错误
  • 逻辑错误:withdraw方法中写的是balance -=1,应该改为减去传入的取款金额amount,累计取款总额也应该加amount而不是1
  • 拼写错误:存在num_deposit与num_deposits名称不一致、BankAcconut2拼写错误的问题
  • 方法调用缺失self.:内部调用numDeposits()要写为self.numDeposits()

修复后完整代码

class BankAccount:
    def __init__(self, balance, name):
        self.balance = balance
        self.name = name
        self.num_deposits = 0
        self.deposit_total = 0
        self.num_withdraws = 0
        self.withdraw_total = 0

    def numDeposits(self):
        self.num_deposits += 1

    def numWithdraws(self):
        self.num_withdraws += 1

    def deposit(self, amount):
        self.balance += amount
        self.deposit_total += amount
        self.numDeposits()

    def withdraw(self, amount):
        self.balance -= amount
        self.withdraw_total += amount
        self.numWithdraws()

    def endOfMonth(self):
        print(f"银行账户:{self.name}")
        print(f"余额:${self.balance}")
        print(f"存款次数:{self.num_deposits} 总金额 ${self.deposit_total}")
        print(f"取款次数:{self.num_withdraws} 总金额 ${self.withdraw_total}")
        print("-"*30)

# 以下代码移到类外部
BankAccount1 = BankAccount(0 , "chase")
BankAccount2 = BankAccount(100, "Bank of America")

BankAccount1.deposit(50)
BankAccount1.deposit(50)
BankAccount1.withdraw(100)
BankAccount1.withdraw(100)
BankAccount1.withdraw(100)
BankAccount1.endOfMonth()

BankAccount2.deposit(25)
BankAccount2.deposit(25)
BankAccount2.deposit(5000)
BankAccount2.withdraw(10)
BankAccount2.withdraw(1000)
BankAccount2.withdraw(70)
BankAccount2.endOfMonth()

运行输出

银行账户:chase
余额:$-200
存款次数:2 总金额 $100
取款次数:3 总金额 $300
------------------------------
银行账户:Bank of America
余额:$4045
存款次数:3 总金额 $5050
取款次数:3 总金额 $1080

完全符合你预期的输出要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:45:04