为什么这个班级课程没有返回余额?

时间:2015-11-12 19:45:01

标签: python class account

问题:开发支持这些方法的类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

2 个答案:

答案 0 :(得分:0)

return self.balance

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

答案 1 :(得分:0)

余额定义应如下:

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