Skip to main content
 首页 » 编程设计

python之银行账户类。如何让它更强大/更高效 (面向对象)

2025年05月04日10hnrainll

我想让这个程序在不使用全局变量的情况下运行。基本上,如果此人退出并最终变成负数,他们将受到 5 的惩罚。每笔交易出现负数也会导致 5 的惩罚。

假设只有 2 个帐户,该程序似乎运行良好:

account1 = Bankaccount(20) 
account2 = Bankaccount(5) 

但这就是它的局限性。我怎样才能允许无限帐户?所以我不会局限于这两个全局变量。我希望这是有道理的,假设我必须更改取款功能和 get_fees,但我是 OOP 的新手,所以我被卡住了。感谢您的帮助!

pen = 0 
pen2 = 0 
 
 
class BankAccount: 
 
 
 def __init__(self, initial_balance): 
        """Creates an account with the given balance.""" 
        self.money = initial_balance 
 
    def deposit(self, amount): 
        """Deposits the amount into the account.""" 
        self.money += amount 
        return self.money 
 
    def withdraw(self, amount): 
        """ 
        Withdraws the amount from the account.  Each withdrawal resulting in a 
        negative balance also deducts a penalty fee of 5 dollars from the balance. 
        """ 
        global pen, pen2 
        penalty = 5 
 
        if self.money - amount < 0: 
            self.money -= (amount + penalty) 
            if self == account1: 
                pen += 5 
            elif self == account2: 
                pen2 += 5 
        else: 
            self.money -= amount 
        return self.money 
 
 
    def get_balance(self): 
        """Returns the current balance in the account.""" 
        return self.money 
 
    def get_fees(self): 
        """Returns the total fees ever deducted from the account.""" 
        global pen, pen2 
        if self == account1: 
            return pen 
        elif self == account2: 
            return pen2 

请您参考如下方法:

让惩罚成为一个实例属性,就像money一样:

def __init__(self, initial_balance): 
        """Creates an account with the given balance.""" 
        self.money = initial_balance 
        self.penalty = 0 

然后,稍后:

def withdraw(self, amount): 
 
    if self.money - amount < 0: 
        self.penalty += 5