Python类属性访问报错AttributeError,如何跨方法访问类属性?
访问bank_Customer类属性触发AttributeError的问题
我是Python新手,尝试访问bank_Customer类的acnt_amount属性时触发AttributeError错误。请问如何在类的getDetails方法与withdraw方法之间访问属性?我犯了什么错误?恳请帮助,谢谢!
代码:
class bank_Customer: def getDetails(self, cname, acnt_no, acnt_type, acnt_amount): self.cname = cname self.acnt_no = acnt_no self.acnt_type = acnt_type self.acnt_amount = acnt_amount row = self.cname + "," + str(self.acnt_no) + "," + self.acnt_type + "," + str(self.acnt_amount) + "\n" file = open('cust_details.csv','a') file.write(str(row)) file.close() print('*'*40) print("Account has been added successfully!") return self.acnt_amount def withdraw(self): cash = int(input("Please enter the amount to be withdrawn: ")) self.acnt_amount = self.acnt_amount - cash f"balance amount is {balance}" return balance base = bank_Customer() base.withdraw()
错误信息:
Traceback (most recent call last): File "C:\Users\kisha\IdeaProjects\Git projects in python\ATM application.py", line 96, in <module> base.withdraw() File "C:\Users\kisha\IdeaProjects\Git projects in python\ATM application.py", line 66, in withdraw self.acnt_amount = self.acnt_amount - cash AttributeError: 'bank_Customer' object has no attribute 'acnt_amount'
问题原因
- 属性未初始化就访问:你创建
bank_Customer对象后直接调用withdraw(),但acnt_amount属性仅在getDetails()方法中赋值,此时对象还未拥有该属性,必然触发AttributeError。 - withdraw方法变量未定义:方法内使用的
balance变量没有声明,应该用self.acnt_amount替代。
修复方案
方案一:先初始化属性再调用取款方法
修改主代码逻辑,先调用getDetails()完成属性初始化:
base = bank_Customer() # 先传入客户信息初始化所有属性 base.getDetails("张三", 123456, "储蓄卡", 10000) # 再执行取款操作 base.withdraw()
方案二:用构造方法规范初始化(更推荐)
Python类推荐用__init__构造方法初始化属性,替代自定义的getDetails,代码更符合规范:
class BankCustomer: # 类名改用大驼峰,符合PEP8规范 def __init__(self, cname, acnt_no, acnt_type, acnt_amount): self.cname = cname self.acnt_no = acnt_no self.acnt_type = acnt_type self.acnt_amount = acnt_amount self._save_to_file() print('*'*40) print("Account has been added successfully!") # 把文件写入逻辑抽成私有方法,职责更清晰 def _save_to_file(self): row = f"{self.cname},{self.acnt_no},{self.acnt_type},{self.acnt_amount}\n" # 用with语句自动关闭文件,避免资源泄漏 with open('cust_details.csv','a') as file: file.write(row) def withdraw(self): cash = int(input("请输入取款金额:")) # 增加余额校验,避免出现负数 if cash > self.acnt_amount: print("余额不足,无法完成取款") return self.acnt_amount self.acnt_amount -= cash balance = self.acnt_amount print(f"当前余额为:{balance}") return balance # 创建对象时直接传入初始化信息 base = BankCustomer("张三", 123456, "储蓄卡", 10000) base.withdraw()
额外提示
- 类名遵循PEP8规范,用大驼峰命名(如
BankCustomer而非bank_Customer)。 - 文件操作优先使用
with语句,自动处理文件关闭,更安全可靠。 - 取款逻辑建议增加余额校验,避免出现不合理的负数余额。
内容的提问来源于stack exchange,提问作者Kishan
相关产品推荐
相关产品推荐

