Python中的封装和约束

Python中的封装和约束,python,python-3.x,oop,encapsulation,Python,Python 3.x,Oop,Encapsulation,我有一个测试程序: class BankAccount: def __init__(self, name, balance): self.name = name self.balance = balance self.transaction_fee = 5.00 def deposit(self, amount): self.balance = self.balance + amount def

我有一个测试程序:

class BankAccount:
     def __init__(self, name, balance):
         self.name = name
         self.balance = balance
         self.transaction_fee = 5.00
     def deposit(self, amount):
        self.balance = self.balance + amount
     def withdraw(self, amount):
        self.balance = self.balance - amount
我通过以下操作封装了余额、名称和交易费:

class BankAccount:
     def __init__(self, name, balance):
         self._name = name
         self._balance = balance
         self._transaction_fee = 5.00
     def deposit(self, amount):
        self._balance = self._balance + amount
     def withdraw(self, amount):
        self.balance = self.balance - amount
现在我需要修改BankAccount类,以强制执行帐户余额永远不能变为负值的不变量。这意味着你应该禁止负存款和超过账户余额的取款

我曾想过在存款和取款功能中使用if/else语句。例如:

 def deposit(self, amount):
    if amount >= 0:
          self._balance = self._balance + amount
    else ?????
另一方面,我不知道如何使它返回函数并再次请求一个合适的值

还有其他方法可以做到这一点吗


感谢您的方法,您可以返回一个表示成功或失败的布尔值。然后调用代码可以适当地处理它

如果您担心调用代码可能会忽略返回值,而事务会以静默方式失败,那么您可以引发一个异常,让调用代码来处理该异常-类似这样:

class BankAccount:
     def __init__(self, name, balance):
         self._name = name
         self._balance = balance
         self._transaction_fee = 5.00
     def deposit(self, amount):
        if (self._balance + amount) < 0:
            raise Exception("Balance cannot go below 0.")
        else:
            self._balance = self._balance + amount
     def withdraw(self, amount):
        if (self._balance - amount) < 0:
            raise Exception("Balance cannot go below 0.")
        else:
            self._balance = self._balance - amount
类别银行账户:
定义初始(自我、姓名、余额):
self.\u name=name
自我平衡=平衡
自助交易费用=5.00
def保证金(自身、金额):
如果(自身余额+金额)<0:
引发异常(“余额不能低于0”)
其他:
自身余额=自身余额+金额
def提取(自身、金额):
如果(自身余额-金额)<0:
引发异常(“余额不能低于0”)
其他:
自身余额=自身余额-金额

在现实生活中,您将创建自己的Exception子类并引发该异常。

处理该异常的一种方法是为该模块定义一个异常类(例如,
AccountError
),并在有人试图存入负金额(或做任何其他不允许的事情)时引发该异常

在调用
deposit()
方法的地方,您可以捕获异常(借助
try
-
除外
-块),并允许用户在输入无效值时重试

可能是这样的:

class BankAccount:
     def __init__(self, name, balance):
         self._name = name
         self._balance = balance
         self._transaction_fee = 5.00
     def deposit(self, amount):
        if (self._balance + amount) < 0:
            raise Exception("Balance cannot go below 0.")
        else:
            self._balance = self._balance + amount
     def withdraw(self, amount):
        if (self._balance - amount) < 0:
            raise Exception("Balance cannot go below 0.")
        else:
            self._balance = self._balance - amount
class AccountError(异常):
“”“模块特定错误”“”
类别银行户口:
...
...
...
def保证金(自身、金额):
如果金额>=0:
自身余额=自身余额+金额
其他:
raise AccountError(“存款金额不能为负数”)
(当然,您可以向异常添加更多信息和功能。)

在调用代码的地方:

account = BankAccount()
...
...
try:
    account.deposit(negative_amount)
except AccountError as exc:
    # Code that allows you to retry the deposit.
    # Implementation depends on your program structure.
整个块可以嵌入
for
循环中,同时进行一定量的重试,或者在您的情况下进行任何有意义的操作


具体实施将取决于程序的结构和功能。

如果您在
deposit()
方法中强制执行非负金额,则不需要
其他:
。如果您在存款()之外强制执行此操作,那么您可以对此采取一些措施。