为什么这个类程序不返回余额?

2024-10-03 09:07:43 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:开发一个支持这些方法的类BankAccount__init__():将银行帐户余额初始化为输入参数的值,如果未给定输入参数,则初始化为0

withdraw():将一个参数作为输入并从余额中取出

deposit():以一个数量作为输入,并将其添加到余额中

balance():返回帐户的余额

class ValueErrorException (Exception):
    pass

class BankAccount:

    accounts = 0

    def __init__ (self, bal = 0.0):
        BankAccount.accounts += 1
        self.accountNumber = str(BankAccount.accounts)
        self.balance = bal


    def withdraw(self, amount):
        if self.balance - amount < 0:
            raise ValueErrorException("Illegal balance")
        else:
            self.balance -= amount


    def deposit (self, amount):
        self.balance += amount


    def balance(self, amount):
        return amount

Tags: 方法self参数initdefamountclass余额
2条回答

余额的定义应该是这样的:

def balance(self):
    return self.balance

您还可以考虑将变量名从balance更改为accountBalance,这样就不会影响命名相同的定义。你的新代码现在应该是:

^{pr2}$

return self.balance

访问classes实例变量,而不是函数参数。不需要将amount传递给函数只是为了返回它

相关问题 更多 >