class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
a = Account(1000.00)
a.deposit(550.23)
a.deposit(100)
a.withdraw(50)
print a.getbalance()当我运行这段代码时,我得到了这个错误。AttributeError:帐户实例没有“”deposit“”属性“
发布于 2010-06-13 10:04:11
所以上面的答案意味着你的代码应该是这样的--记住,与其他语言不同,缩进在Python中是一件严肃的事情:
class Account(object):
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance += amt
def withdraw(self, amt):
self.balance -= amt
def getbalance(self):
return self.balance
a = Account(1000.00)
a.deposit(550.23)
a.deposit(100)
a.withdraw(50)
print a.getbalance()现在你会得到1600.23,而不是一个错误。
发布于 2010-06-12 08:48:24
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance按照您定义它们的方式,它们对于__init__方法是本地的,因此无用。
发布于 2010-06-12 08:48:29
你把它们缩得太深了。它们是__init__()方法的内部函数。
https://stackoverflow.com/questions/3027048
复制相似问题