2014-01-07 99 views
-1

我想了解我收到的錯誤消息(問題主題行)。我懷疑它可能與範圍和嵌套邏輯有關。AttributeError:'NoneType'對象沒有屬性'輸入'

這裏是有問題的代碼塊:

class Smaug(Scene): 

def enter(self): 
    print "Smaug is a terrifying huge fire breathing dragon, but you must get the Arkenstone from him for Thorin"  
    print "In Smaug's cave, the Lonely Mountain, Smaug notices your presence and challenges you to a game" 
    print "He says \"Guess a number between 1 and 3\"" 
    smaugNum = random.randint(1, 3) 
    guesses = 0 

    def guess(): 

     while guesses < 4: 
      print "Guess a number between 1 and 3" 
      numb = raw_input("> ") 

      if numb == smaugNum: 
       print "Well done! You win." 
       Player.BilbosStuff.append('arkenstone') 
       print "Now Bilbo has", Player.BilbosStuff 
       return 'finished' 

      else: 
       print "You lose!" 
       guesses += 1 
       guess() 

     print "Too many failed guesses, you lose!" 
     return 'death' 

的代碼塊運行與發動機,這是一類:

class GameEngine(object): 

    def __init__(self): 
     self.scenes = {'TheTrolls':TheTrolls(), 'MistyMountainsAndGollum':MistyMountainsAndGollum(), 'Smaug':Smaug(), 'death':death()} 

    def run(self): 

     next = 'TheTrolls' 
     while True: 
      if next == 'finished': 
       print "Well done! You won!" 
       exit(1) 
      next = self.scenes.get(next).enter() 


GameEngine().run() 

「遊戲」(這是一個教程中,我通過)在向Smaug()添加guess()函數之前做了工作。

但這裏是輸出:

Traceback (most recent call last): File "ex45.py", line 21, in 
<module> 
    GameEngine().run() File "ex45.py", line 18, in run 
    next = self.scenes.get(next).enter() AttributeError: 'NoneType' object has no attribute 'enter' 

我的思路是沿着在while循環也許return 'finished'不是母塊的回行?還是我離開?我是一名學習者。

+0

您需要在代碼中鍵入... – qwertynl

+0

難道不是縮進嗎?在我看來「高清輸入(自我)」是在同級比Smaug級... –

+0

感謝您的提示,我檢查了但我認爲這只是堆棧溢出自動格式化時,我粘貼 - 高清輸入(自):從父母縮進 –

回答

1

您的問題是,以代碼的形式:

if next not in scenes: 
    scenes.get(next) == None 

因此錯誤:爲消息告訴你,None沒有一個enter屬性!嘗試

next = scenes.get(next) 
if next is not None: 
    next.enter() 
else: 
    print("No more scenes") 
    break # leave the loop 
+0

感謝您的答案,但創建了一個無限循環「沒有更多的場景」。 –

+0

然後,當你到達那個點時,從你的循環中「突破」! – jonrsharpe

+0

或'try:next = self.scenes.get(next).enter(); AttributeError除外:print(「No more scenes」); break' – SethMMorton

0

從錯誤中可以看到self.scenes.get(next)結果在None。可能有很多原因,但我想這是death()調用返回None。

+0

爲什麼死亡調用不會返回?它存在於dict中,並且當while循環運行的條件爲false時返回(應該) –

+0

你有'self.scenes = {'TheTrolls':TheTrolls(),'MistyMountainsAndGollum':MistyMountainsAndGollum(),'Smaug ':Smaug(),'death':death()}'正如我所說'self.scenes.get(something)'返回None。字典中的所有其他值似乎都是類實例,所以只留下'death()'。 –