困惑于学习Python的艰难之路ex43中的课程?

时间:2013-08-13 00:56:34

标签: python class oop

我对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()

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

Engine实例的scene_mapMap类的一个实例,就像全局a_map一样。实际上,a_game.scene_map与<{1}}是相同的实例。

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

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

嗯,可以。问题是,如果你这样做,你将无法创建两个a_map个实例,而不会在同一个Engine上进行争夺。 (这与您不希望在函数中使用全局变量的原因相同。对象不会添加新问题 - 事实上,对象的主要部分是解决全局 - 变量问题。)