如何限制实例变量值不超出定义的限制

时间:2015-12-12 14:38:21

标签: python oop

以下代码导致负余额。我没有在撤销方法中设置if条件,而是寻找其他方法来检查并限制余额变为负数。

class Customer(object):

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

    def withdrawl(self, amount):
        self.balance -= amount
        return self.balance

jeff = Customer(1000.0)
print jeff.withdrawl(2000)

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

class Balance():

    def __init__(self,x):
        assert x >= 0, "Balance can't be negative!"
        self.value = x

class Customer(object):

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

    def withdrawl(self, amount):
        self.balance = Balance(self.balance.value - amount)
        return self.balance

jeff = Customer(Balance(1000.0))
print jeff.withdrawl(2000)

但这似乎对我来说太过分了。为什么不使用if语句?