2013-10-09 96 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名稱是誤導。它不會從某種內在排序中給出「下一個」場景,而是它返回一個你選擇的場景,大概是你想要選擇的下一個場景。

相關問題