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



我对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。(这与你不想在函数中使用全局变量的原因相同。对象不会添加新问题——事实上,对象的很大一部分是解决全局变量问题。)

最新更新