【问题标题】:dataclass set new value after declaring one声明一后数据类设置新值
【发布时间】:2021-09-28 03:56:00
【问题描述】:
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', 70, 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'


我尝试实现一个小银行类。当我在下面进行测试时,我注意到我无法更改布尔值。变量不是私有的,为什么这不起作用?

【问题讨论】:

    标签: class python-dataclasses


    【解决方案1】:

    您实际上可以更改布尔值,并且您正在这样做,由于其他条件内部检查方法,您的代码会引发值错误:

     if other.balance < money:
            raise ValueError
    

    在测试中,Jeff 的余额为 70,而您尝试按照 money 参数指定的方式获得 80,因为 70 小于 80,因此会引发 Value Error。

    如果您没有调试工具,我建议您在对程序的最终输出感到困惑时打印不同状态的变量。

    您可以通过在错误之前打印它的值来验证布尔值是否已更改为 True。

    【讨论】:

    • 啊,是的,谢谢,我看看如果我没有评论其他语句,我会得到正确的输出
    • 没问题,如果对你有帮助,别忘了把答案标记为正确
    猜你喜欢
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多