为什么这个 class 程序没有 return 余额?

Why does this class program not return the balance?

问题:开发一个支持这些方法的classBankAccount__init__():将银行账户余额初始化为输入参数的值,如果没有给出输入参数则初始化为 0

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

deposit():取一个金额作为输入,添加到余额中

balance():Returns账户余额

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

return self.balance

访问 类 实例变量,而不是函数参数。无需将 amount 传递给函数只是为了 return it

余额定义应该是这样的:

def balance(self):
    return self.balance

您可能还想考虑将变量名称从 balance 更改为 accountBalance,这样它就不会影响同名的定义。您的新代码现在是:

class ValueErrorException (Exception):

    pass

class BankAccount:

    accounts = 0

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


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


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


    def balance(self):
        return self.accountBalance