有人可以解释这个简短的python方法

时间:2013-10-09 07:45:23

标签: python class methods

我正在学习Python教程,但不理解这门课程。 http://learnpythonthehardway.org/book/ex43.html

有人可以向我解释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)

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

return Map.scenes.get(scene_name)

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

它类似于:

return scenes[scene_name]

如果密钥不存在而不是引发KeyError,则返回None

答案 2 :(得分:0)

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

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

传递the_bridge时,它会检查班级中的词典scenes并尝试从中获取您选择的场景。

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

答案 3 :(得分:0)

next_scene名称具有误导性。它不会从某些内在排序中给出“下一个”场景,而是返回您选择的场景,可能是您想要选择的下一个场景。