gpt4 book ai didi

python - 对 Learn Python the Hard Way ex43 中的类感到困惑?

转载 作者:行者123 更新时间:2023-11-28 16:42:04 24 4
gpt4 key购买 nike

我对 Map 和 Engine 类如何一起工作来运行这个 Adventureland 类型的游戏感到困惑(完整代码在这里:http://learnpythonthehardway.org/book/ex43.html)。我想我了解 Map 类中发生的事情,但我真的对 Engine() 中发生的事情以及为什么需要 scene_map 变量感到困惑。

class Map(object):

scenes = {
'central_corridor': 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)

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()
current_scene = self.scene_map.next_scene(next_scene_name)

a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

感谢您的帮助。

最佳答案

Engine 实例的scene_mapMap 类的实例,就像全局a_map 一样。事实上,a_game.scene_mapa_map 相同的实例。

因此,无论您可以在顶层用 a_map 做什么,Engine.play 代码都可以用 self.scene_map 做。将 a_map 定义之前的所有内容都输入到交互式解释器中并尝试使用 a_map 以确保您知道它究竟能为您做什么可能是值得的。

那么,为什么Engine需要self.scene_map呢?为什么它不能只使用全局 a_map

好吧,它可以。问题是,如果您这样做,您将无法创建两个 Engine 实例,除非它们争夺同一个 a_map。 (这与您不想在函数中使用全局变量的原因相同。对象不会增加新问题——事实上,对象的很大一部分是解决全局变量变量问题。)

关于python - 对 Learn Python the Hard Way ex43 中的类感到困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18199031/

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