gpt4 book ai didi

python - 艰难地学习 Python 示例 #43

转载 作者:行者123 更新时间:2023-11-28 22:43:08 24 4
gpt4 key购买 nike

我正在学习 Zed Shaw 的 LearnPythontheHardWay,但我被难住了。

我收到错误:

[Attribute Error:'NoneType' object has no attribute 'enter']

在行:Engine 类下的 next_scene_name = current_scene.enter()

from sys import exit

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()
last_scene = self.scene_map.next_scene('finished')

while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)

current_scene.enter()

class EmptyScene(Scene):

def enter(self):
pass

class FinishScene(Scene):

def enter(self):
pass

class Map(object):

scenes = {
'empty_scene': EmptyScene(),
'finished': FinishScene(),
}

def __init__(self, start_scene):
self.start_scene = start_scene

def next_scene(self, scene_name):
val = Map.scenes.get(scene_name)
return val

def opening_scene(self):
return self.next_scene(self.start_scene)


a_map = Map('empty_scene')
a_game = Engine(a_map)
a_game.play()`

最佳答案

问题是 current_scene 实际上是 None。这是由于 self.scene_map.next_scene 调用 dict.get 引起的。使用 dict.get 的问题在于,如果键不在字典中,那么它只会返回 None 而不是像您期望的那样抛出异常。因此,您的程序会继续运行,认为一切正常,直到代码稍后出现问题。

关于python - 艰难地学习 Python 示例 #43,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31065462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com