【问题标题】:How to restrict an instance variable value not to go beyond the limits defined如何限制实例变量值不超出定义的限制
【发布时间】:2015-12-12 14:38:20
【问题描述】:

以下代码导致负余额。我没有在提款方法中设置 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)

提前致谢

【问题讨论】:

  • 我正在寻找添加条件以外的方法。我不知道 python 在实现相同目标方面的范围。
  • 避免使用关键字的理由是什么?
  • self.balance -= amount * (self.balance >= amount)
  • 想知道,这是否在范围内。不知道如何在教程中搜索相同的内容。使用关键字解析,我知道。
  • 正如 falsetru 所证明的,您不需要使用if 声明。另一种选择是使用自定义对象来存储永远不会为负的值,但该对象的代码需要使用if 语句或类似于 falsetru 示例中的语法。 OTOH,Python 的禅宗说:“显式胜于隐式”。如果尝试提取的金额超过当前余额,您肯定不想默默地将余额限制为零。您不也想生成某种警告或错误消息吗?

标签: python oop


【解决方案1】:

你可以这样做:

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 语句?

【讨论】:

    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 2020-04-22
    • 2022-01-19
    • 2021-09-03
    • 2011-08-10
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多