2013-10-09 85 views
0

我正在学习Python教程,但不理解这个类。 http://learnpythonthehardway.org/book/ex43.html有人可以解释这个简短的Python方法

有人可以向我解释next_scene方法是如何工作的。 为什么它切换到下一个场景?

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) 
+0

它不切换到* next *场景。它切换到您在传递给函数的参数中指定的场景。 – Lix

+0

我不太确定你在这里问的是什么......你面临的问题到底是什么? – Lix

回答

0

它也会根据具体取决于您传递给它的关键字scenes字典场景的对象,并返回回给你。

为什么它切换到下一个场景?

它切换到下一个场景的原因是因为在基类各场景扩展指定的序列中的下一个场景它完成通过enter()功能运行后:

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() # returns next scene key 
      current_scene = self.scene_map.next_scene(next_scene_name) # initiates next scene and sets it as `current_scene` 

例如,CentralCorridor场景最后根据输入的动作返回下一个场景的关键字:

def enter(self): 
    print "The Gothons of Planet Percal #25 have invaded your ship and destroyed" 
    ... 
    print "flowing around his hate filled body. He's blocking the door to the" 
    print "Armory and about to pull a weapon to blast you." 

    action = raw_input("> ") 

    if action == "shoot!": 
     print "Quick on the draw you yank out your blaster and fire it at the Gothon." 
     ... 
     print "you are dead. Then he eats you." 
     return 'death' # next scene `Death` 

    elif action == "dodge!": 
     print "Like a world class boxer you dodge, weave, slip and slide right" 
     ... 
     print "your head and eats you." 
     return 'death' # next scene `Death` 

    elif action == "tell a joke": 
     print "Lucky for you they made you learn Gothon insults in the academy." 
     ... 
     return 'laser_weapon_armory' # next scene `LaserWeaponArmory` 

    else: 
     print "DOES NOT COMPUTE!" 
     return 'central_corridor' # next scene `CentralCorridor` 

并且整个序列以死亡场景的结尾enter()功能退出程序:

def enter(self): 
    print Death.quips[randint(0, len(self.quips)-1)] 
    exit(1) 
+0

谢谢,我没有注意到!这使得它更加清晰。 – Christoph

0

return Map.scenes.get(scene_name)

Map.scenes是在你的类中定义的字典。调用.get()就可以得到给定密钥的值。在这种情况下给出的关键是scene_name。然后该函数返回一个场景的一个实例。

它类似于:

return scenes[scene_name] 

除了没有养KeyError异常,如果该键不存在,None返回。

0

在方法next_scene中,您将传递一个scene_name变量。

test_map = Map('central_corridor') 
test_map.next_scene('the_bridge') 

当它传递the_bridge,它会检查字典scenes在类,并试图从中获得你所选择的场景。

使用get方法,因此如果您要调用具有无效场景名称的方法(例如test_map.next_scene('the_computer),则不会引发KeyError异常。在这种情况下,它只会返回None

0

next_scene名称是误导。它不会从某种内在排序中给出“下一个”场景,而是它返回一个你选择的场景,大概是你想要选择的下一个场景。

相关问题