[英]How to debug an AttributeError in Python?
因此,我一直在研究Zed Shaw的“ 學習Python的艱難方法” ,並且在練習43(通過使用面向對象的編程原理創建一個非常簡單的基於文本的游戲)之前取得了不錯的成績。 我反復得到屬性錯誤,更具體地說:
File "PracticeGame.py", line 206, in <module>
a_game.play()
File "PracticeGame.py", line 20, in play
next_scene_name = current_scene.enter()
AttributeError: 'NoneType' object has no attribute 'enter'
我已經看到有關此錯誤的多個帖子,但是沒有一個答案能以我能理解的方式真正解釋過此問題,也沒有提供的解決方案對我有用。 以下是代碼中的行,包括第20行:
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n-------"
next_scene_name = current_scene.enter() #this is line 20
current_scene = self.scene_map.next_scene(next_scene_name)
return current_scene
這是包含第206行的代碼的結尾
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play() #line 206
地圖定義為:
class Map(object):
scenes = {
'central_cooridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
我從不同的帖子中了解到,此錯誤消息表示未定義第20行的某些部分,但是我對未定義的內容及其發生原因感到迷惑。 我是Python的新手。
您的錯誤提示'NoneType' object has no attribute 'enter'
。 這意味着您有一些類型為NoneType
對象,並且您正在嘗試訪問名為enter
屬性。 現在,Python確實有一個類型為NoneType
: None
。 因此,編譯器試圖告訴您您正在執行X.enter
並且X
為None
。
現在讓我們看一下上下文。 上下文是: File "PracticeGame.py", line 20, in play next_scene_name = current_scene.enter()
從第一段開始,錯誤是current_scene
為None
。 現在,您想通過程序向后追溯,並找出current_scene
來源。 在您的情況下,它來自Map.scenes.get(scene_name)
,其中scene_name = 'central_corridor'
。 map.get
密鑰,則map.get
返回None,所以這一定是您的問題。 您仔細觀察,發現您在地圖定義'central_cooridor'
場景名稱誤拼為'central_cooridor'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.