2015-12-14 73 views
1

我的代碼在python下面一行:AttributeError的在我的Python代碼2

class BankAccount: 
    def __init__ (self,balance = 0): 
    self.balance = balance 

    def deposit(self, deposit_amount= 30): 
     self.deposit_amount=deposit_amount 
     balance += deposit_amount 
     return balance 

     def withdraw (self,withdraw_amount= 10): 
     if withdraw_amount > balance: 
      raise RuntimeError('Invalid Transaction') 
      balance -= withdraw_amount 
      return balance 

      class MinimumBalanceAccount(BankAccount): 
      def __init__(self,balance = 0): 
       self.balance = balance 

       c = BankAccount() 
       c.deposit(50) 

它給了我這個錯誤:

AttributeError("BankAccount instance has no attribute 'deposit'" 
+0

更換c = BankAccount()做你已經有了一些縮進和格式問題 – CoryKramer

+1

你的縮進遍佈各處。你能糾正它,請匹配你的實際代碼? –

+0

不相關但很重要:在Python 2中,_always_從'object'派生頂級類:即,像這樣定義它:'class BankAccount(object):...'。如果你不這樣做,你將看不到所有記錄的對象和類的行爲。 – alexis

回答

0

如果你的縮進實際上是因爲你的貼吧,然後deposit函數在__init__方法中定義。因此,這不是該課程的一個屬性,而是一種僅在__init__方法中可用的功能。下面的代碼僅僅是你的代碼的副本,但縮進固定:

class BankAccount: 
    def __init__(self,balance=0): 
     self.balance = balance 

    def deposit(self, deposit_amount=30): 
     self.deposit_amount=deposit_amount 
     self.balance += deposit_amount 
     return self.balance 

    def withdraw(self,withdraw_amount=10): 
     if withdraw_amount > self.balance: 
      raise RuntimeError('Invalid Transaction') 
     self.balance -= withdraw_amount 
     return self.balance 

class MinimumBalanceAccount(BankAccount): 
    def __init__(self,balance = 0): 
     self.balance = balance 

c = BankAccount() 
c.deposit(50) 

此代碼對我的作品,因爲它的時候我c = MinimumBalanceAccount()

+0

非常感謝。 –

+0

請在第16行第16行中更正BankAccount 類MinimumBalanceAccount(BankAccount): NameError:名稱'BankAccount'未定義 –

+0

只要BankAccount的類定義已完成,應定義「BankAccount」 。我猜你試圖在BankAccount本身的定義中實例化('BankAccount()'),但是我沒有看到代碼就說不清楚。另外請記住,在上面發佈的代碼中,MinimumBalanceAccount繼承自BankAccount,但是您會覆蓋'__init__'方法。如果您希望它仍像常規BankAccount一樣初始化,請在MinimumBalanceAccount的__init__' – acdr

相關問題