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

标签 python oop python-2.7

我想让这个程序在不使用全局变量的情况下运行。基本上,如果此人退出并最终变成负数,他们将受到 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

关于python - 银行账户类。如何让它更强大/更高效? (面向对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20076869/

相关文章:

python - 需要多少个数字才能使返回值等于整数 N?

python - 如何在我的图中获得最长最短路径?

python - 除非 root 用户,否则无法导入 python 模块

python - 将表情符号添加到 AFINN 库以进行情感分析

python - 使用 10**9 的成本超过 1000000000?

python - django - 类型错误 : coercing to Unicode

python - 为什么使用 Tensorflow-Hub KerasLayer 会出现 'Connecting to invalid output of source node' 错误?

c++ - 如何实现具有循环引用的对象的深拷贝或克隆?

python - python 中的面向对象设计问题,has-a 与 is-a

javascript - 实现原型(prototype)继承的正确方式