我有一个 BankAccount 类,它允许设置余额、要存入/提取的金额,然后是一个返回余额的方法。
class BankAccount():
def __init__(self, initialBalance = 0):
self.balance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self.balance))
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def balance(self):
return(self.balance())
但是当我调用平衡方法 (b.balance()) 时,它得到一个 float object not callable 错误。但是,如果我将其命名为 b.balance,它会返回正确的金额。我对错误的含义以及方法调用为何不起作用感到困惑。提前致谢!
请您参考如下方法:
属性和方法同名是行不通的。您可以为该属性指定一个不同的名称:
class BankAccount():
def __init__(self, initialBalance = 0):
self._balance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self._balance))
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
self._balance -= amount
def balance(self):
return(self._balance)
print(BankAccount())
或直接访问属性(并删除访问器方法):
class BankAccount():
def __init__(self, initialBalance = 0):
self.balance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self.balance))
def __repr__(self):
return("BankAccount({})".format(self.balance))
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
print(BankAccount())
