Python账户类Deposit方法返回None问题排查及代码错误分析
存取款程序存款方法返回None的问题排查与修复
核心问题原因
- 存款方法
deposit错误引用了类属性self.depositAmnt(初始值为0),而非传入的方法参数depositAmnt,导致判断条件if self.depositAmnt >= 1永远不成立,方法未执行return语句,默认返回None。 - 取款方法
withdraw存在同样逻辑错误,误用类属性而非参数,会导致取款操作也无法正常执行。
代码中的具体错误
存款方法判断与累加逻辑错误
原代码片段:def deposit(self, depositAmnt ): if self.depositAmnt >= 1 : self.__balance = self.__balance + self.depositAmnt return self.__balance这里错误使用类属性
self.depositAmnt做判断和累加,实际应该用传入的方法参数depositAmnt。取款方法判断与扣款逻辑错误
原代码片段:def withdraw(self, withDrawalAmount): if self.__balance >= self.withDrawalAmount: self.__balance = self.__balance - self.withDrawalAmount return self.__balance同样误用类属性
self.withDrawalAmount,应该使用传入的参数withDrawalAmount。方法缺少默认返回值
当存款/取款条件不满足时,方法没有定义返回值,会默认返回None,建议补充默认返回逻辑。
修正后的代码
print("Hello !!! Welcome to Deposit & Withdrawal Machine") class Account: def __init__(self, ID=0, balance=100, annual_interest_rate=0): self.__ID = ID self.__balance = balance self.__annual_interest_rate = annual_interest_rate # setters def setId(self, ID): self.__ID = ID def setBal(self, Bal): self.__balance = Bal def setAnnualInterestRate(self, annualIntrstRate): self.__annual_interest_rate = annualIntrstRate # getters def getId(self): return self.__ID def getBal(self): return self.__balance def getAnnualIntrstRate(self): return self.__annual_interest_rate # special getters def getMonthlyInterestRate(self): annual_rate = self.__annual_interest_rate / 100 monthly_rate = annual_rate / 12 return monthly_rate def getMonthlyInterest(self): # 先确保计算过月利率,避免属性未定义报错 monthly_rate = self.getMonthlyInterestRate() return self.__balance * monthly_rate # other methods def withdraw(self, withDrawalAmount): if self.__balance >= withDrawalAmount: self.__balance -= withDrawalAmount return self.__balance # 无论是否取款成功,都返回当前余额 def deposit(self, depositAmnt ): if depositAmnt >= 1 : self.__balance += depositAmnt return self.__balance # 无论是否存款成功,都返回当前余额 client001 = Account(1122, 20000, 4.5) print("Your Balance After withdrawal is : ", client001.withdraw(2500)) print("Your Balance After deposit is : ", client001.deposit(3000)) print("Your Account ID is : ", client001.getId()) print("Your Current Balance is : ", client001.getBal()) print("Your Monthly Intrst Rate is : ", client001.getMonthlyInterestRate()) print("Your Monthly intrst is : ", client001.getMonthlyInterest())
修正后效果
执行后存款操作会返回预期的20500(初始20000-取款2500+存款3000=20500),所有方法都会返回有效余额而非None。
内容的提问来源于stack exchange,提问作者dareen42
相关产品推荐
相关产品推荐

