【发布时间】: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'
我尝试实现一个小银行类。当我在下面进行测试时,我注意到我无法更改布尔值。变量不是私有的,为什么这不起作用?
【问题讨论】: