class - Confused about classes in Learn Python the Hard Way ex43? -
i'm confused on how map , engine classes work run adventureland type game (full code here: http://learnpythonthehardway.org/book/ex43.html). think understand happening in map class, i'm confused happening in engine() , why scene_map variable needed.
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() thank help.
the engine instance's scene_map instance of map class, global a_map is. in fact, a_game.scene_map same instance a_map.
so, whatever a_map @ top level, engine.play code can self.scene_map. may worth typing interactive interpreter a_map definition , playing around a_map make sure know can you.
so, why engine need self.scene_map? why can't use global a_map?
well, could. problem if did that, wouldn't able create 2 engine instances without them fighting on same a_map. (this same reason don't want use global variables in functions. objects don't add new problem—in fact, big part of objects solving global-variables problem.)
Comments
Post a Comment