Python 如何强制init上的值?
我定义了以下银行账户的类别。帐户应始终以0.0余额开始。即使用户在启动时设置了不同的值,我如何强制该值始终设置为0.0Python 如何强制init上的值?,python,Python,我定义了以下银行账户的类别。帐户应始终以0.0余额开始。即使用户在启动时设置了不同的值,我如何强制该值始终设置为0.0 class Account(object): def __init__(self, name, balance=0.0): self.name = name self.balance = balance def add_money(self, deposit_amnt): self.balance += depos
class Account(object):
def __init__(self, name, balance=0.0):
self.name = name
self.balance = balance
def add_money(self, deposit_amnt):
self.balance += deposit_amnt
def withdraw_money(self, withdraw_amnt):
if withdraw_amnt > self.balance:
raise ValueError('Withdraw amount is more than balance')
else:
self.balance -= withdraw_amnt
def check_balance(self):
return self.balance
my_account = Account('Tim', 15)
my_account.check_balance()
>>> 15
如果要从0开始,可以在
\uuuuu init\uuuu
中使用ommit balance。您必须稍后添加方法来完成此操作
def __init__(self, name):
self.name = name
self.balance = 0
如果要从0开始,可以在
\uuuuu init\uuuu
中使用ommit balance。您必须稍后添加方法来完成此操作
def __init__(self, name):
self.name = name
self.balance = 0
??????
self.balance=0
?只需从\uuuu init\uuuu
中删除balance参数,并将其设置为零即可self.balance=0
?只需将balance参数从\uuuu init\uuuu
中删除,并将其设置为零即可?