如何在Python中调试AttributeError?

时间:2016-11-20 21:33:34

标签: python python-2.7 oop

所以我一直在研究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的新手。

1 个答案:

答案 0 :(得分:0)

您的错误是'NoneType' object has no attribute 'enter'。这意味着您有一些NoneType类型的对象,并且您正在尝试访问名为enter的属性。现在,Python只有NoneType None类型的一个对象。因此,编译器试图告诉您,您正在执行X.enterXNone

现在让我们看看上下文。上下文是: File "PracticeGame.py", line 20, in play next_scene_name = current_scene.enter() 从第一段开始,错误是current_sceneNone。现在,您希望通过该程序向后追溯并找出current_scene来自何处。在您的情况下,它来自Map.scenes.get(scene_name),其中scene_name = 'central_corridor'。如果找不到密钥,map.get将返回None,因此这一定是您的问题。您仔细观察并发现您在地图定义中将场景名称拼错为'central_cooridor'