如何强制init上的值?

2024-04-27 00:05:44 发布

您现在位置: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 

Tags: nameself定义mydefcheck账户account