Python中@property装饰属性未返回实际值问题求助
问题解决:Wallet类调用Balance返回property对象及其他bug修复
核心问题:访问property的方式错误
你在main.py里通过Wallet.Balance访问的是类的property对象,而非实例的余额值。property是绑定到实例的属性,必须通过你创建的wallet实例来访问。同时字符串拼接时需要把浮点型余额转为字符串,否则会触发类型错误。
错误代码:
print("Wallet starting at: " + Wallet.Balance)
修复后代码:
from wallet import Wallet wallet = Wallet(10000) print("Wallet starting at: " + str(wallet.Balance))
类内部变量名不一致的bug
Wallet类的__init__方法初始化的是self.__balance,但Withdraw和Deposit方法里误用了self.__amount,这会导致调用这两个方法时抛出AttributeError(实例不存在__amount私有属性)。
修复后的完整Wallet类代码:
class Wallet: def __init__(self, starting_amount): self.__balance = starting_amount @property def Balance(self): return self.__balance def Withdraw(self, amount: float): if amount <= self.__balance: self.__balance -= amount else: raise Exception("Not enough balance") def Deposit(self, amount: float): self.__balance += amount
额外优化建议
- 给
Withdraw方法增加金额合法性校验,禁止提取负数:def Withdraw(self, amount: float): if amount < 0: raise ValueError("Withdrawal amount cannot be negative") if amount <= self.__balance: self.__balance -= amount else: raise Exception("Not enough balance") - 给
Deposit方法增加金额合法性校验,禁止存入负数:def Deposit(self, amount: float): if amount < 0: raise ValueError("Deposit amount cannot be negative") self.__balance += amount
内容的提问来源于stack exchange,提问作者Mohaje
相关产品推荐
相关产品推荐

