2017-04-05 89 views
0

我試圖在python中添加一個玩家到棋盤上,但我正在努力實現它。嘗試訪問對象函數時Python無類型錯誤

當通過operator庫啓動玩家時,玩家對象的屬性得到驗證。我想在發生異常時顯示它們;即。把每個玩家的初始化放在一個嘗試除外。

問題是,當我做到這一點,因爲我波紋管我得到一個錯誤說:上述

Traceback (most recent call last): File "./main.py", line 88, in move r.forward() AttributeError: 'NoneType' object has no attribute 'forward'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "./main.py", line 161, in main() File "./main.py", line 141, in main move(choice, player) # Peform the moves on the player File "./main.py", line 91, in move Try again!\n>>> ".format(err, r.initial[0], r.initial[1], r.initial[2])) AttributeError: 'NoneType' object has no attribute 'initial'

的操作是由播放器類(player.py)來處理運動。很顯然,我以某種方式返回了一個NoneType,但我不知道爲什麼會出現這種情況。

當我在啓動過程中輸入不正確的玩家位置時,會發生這種情況,然後添加正確的玩家位置。

所以基本上這是我做的:

  1. 啓動板
  2. 啓動播放器的邊界外(或其他玩家)
  3. 啓動一個正確的玩家位置。
  4. 發生錯誤。

但是,如果我正確添加球員(即沒有發生步驟3),則不會有錯誤。

def add_player(board): 

    try: 
     choice = input("Please enter the current player's initial position.\nRemember to keep inside board's limits!\n>>> ").split() 
     if len(choice) == 3 and validate_player(choice[0], choice[1], choice[2]): # Check the length of supplied input and check type-integrity 

      return Player(int(choice[0]), int(choice[1]), choice[2], board)  # Initiate a player with the supplied input. Each player is assigned to a Board (many-to-one relation). 

    except Exception as err: 
     print(err) 
     add_player(board) 
+1

沒有看到調用'forward'的代碼,我們無法診斷問題。請提供[mcve]。 – Kevin

+1

這不直接回答你的問題,但[詢問用戶輸入,直到他們給出有效的回覆](http://stackoverflow.com/q/23294658/953482)可能會給你想法,如何驗證用戶輸入沒有使用遞歸,這可能會使您的堆棧跟蹤更容易理解。 – Kevin

回答

1

這裏有幾個可能的問題。首先,如果if語句不計算爲True,則函數不返回任何內容。不會有任何例外情況發生,因此不會輸入except塊,但不會返回任何其他內容;當沒有其他東西被返回時,None是默認的返回值。

其次,即使出現異常,您也不會將遞歸調用的結果返回到except塊中的add_player。然而,你不應該在這裏使用遞歸,你應該循環直到輸入正確的值。

不相關,但你不應該趕上基地異常;你應該只捕捉你可能期望的事情,在這種情況下,ValueError(如果輸入的是數字以外的其他內容,則來自int調用)和IndexError(如果輸入少於三個項目,則將索引編入列表中)。只抓住這些例外。

相關問題