首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AttributeError救命!

AttributeError救命!
EN

Stack Overflow用户
提问于 2010-06-12 08:47:03
回答 4查看 280关注 0票数 0
代码语言:javascript
复制
  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“”属性“

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-06-13 10:04:11

所以上面的答案意味着你的代码应该是这样的--记住,与其他语言不同,缩进在Python中是一件严肃的事情:

代码语言:javascript
复制
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,而不是一个错误。

票数 2
EN

Stack Overflow用户

发布于 2010-06-12 08:48:24

代码语言:javascript
复制
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__方法是本地的,因此无用。

票数 5
EN

Stack Overflow用户

发布于 2010-06-12 08:48:29

你把它们缩得太深了。它们是__init__()方法的内部函数。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3027048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档