AttributeError帮助!

时间:2010-06-12 00:47:03

标签: python

  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()

运行此代码时出现此错误.NameError:帐户实例没有属性'deposit'

4 个答案:

答案 0 :(得分:5)

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__方法的本地方法,因此无用。

答案 1 :(得分:2)

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

答案 2 :(得分:2)

所以上面的答案意味着你的代码应该是这样的 - 记住与其他语言不同,缩进是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而不是错误。

答案 3 :(得分:0)

除了别人的评论之外:

您没有正确显示实际运行的代码。此处显示的内容def __init__ ...class语句处于同一级别;这会导致(编译时)SyntaxError,而不是(运行时)AttributeError。