如何强制init上的值?

时间:2018-03-20 17:03:40

标签: 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 += 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 

1 个答案:

答案 0 :(得分:5)

如果您想以0开头,可以在__init__中省略余额。您可以添加方法以便稍后执行此操作。

def __init__(self, name):
    self.name = name
    self.balance = 0