如何解决数据类在声明一个后设置新值
from dataclasses import dataclass
@dataclass
class User:
name : str
balance : int
checking_account : bool
def withdraw(self,amount):
if amount > self.balance:
raise ValueError
else:
self.balance -= amount
return self.name + " " + "has" + " " + repr(self.balance) + "."
def check(self,other,money):
if other.checking_account is False:
raise ValueError
if other.balance < money:
raise ValueError
self.balance += money
other.balance -= money
return self.name + " " + "has" + " " + repr(self.balance) + " " + "and" + " " + other.name + " " + "has" + " " + repr(other.balance) + "."
def add_cash(self,amount):
self.balance += int(amount)
return self.name + " " + "has" + " " + repr(self.balance) + "."
Jeff = User("Jeff",70,True)
Joe = User('Joe',False)
print(Jeff.withdraw(2))
#print(Joe.check(Jeff,50))
#print(Jeff.check(Joe,80)) # Raises a ValueError
Joe.checking_account = True
print(Jeff.check(Joe,80)) # Returns 'Jeff has 98 and Joe has 40'
我试图实现一个小的银行类。当我在下面进行测试时,我注意到我无法更改布尔值。变量不是私有的,为什么这不起作用?
解决方法
您实际上可以更改布尔值的值并且您正在这样做,您的代码由于其他条件内部检查方法而引发值错误:
if other.balance < money:
raise ValueError
在测试中,Jeff 的余额为 70,而您正试图按照货币参数指定的方式获得 80,因为 70 小于 80,因此会引发值错误。
如果您没有调试工具,我建议您在对程序的最终输出感到困惑时打印不同状态的变量。
您可以通过在错误之前打印其值来验证布尔值是否已更改为 True。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。