请帮助理解本例中如何使用'return'语句

时间:2012-11-07 01:50:54

标签: python python-2.7

我正在学习使用Learn Python the Hard Way的python并且非常享受它。在其中一个课程示例中,使用了“返回”,我无法理解。

我坚持的教训是Exercise 43: Gothons From Planet Percal #25。我了解到,首次运行游戏时,next_room_name设置为central_corridor,因此central_corridor()会在play()下的第一个循环中调用self.start。 我不明白的是death如何重新分配。

例如,在central_corridor()下返回play(self): while True的情况。在第49行返回后,我们回到next_room_name = self.start循环。第一行是self.start据我所知,central_corridor仍然等于death,但显然现在等于death

这是否意味着在while返回后仍然在play()下的Game()循环中,对象__init__已重新初始化,next_room_name = self.start被喂养的结果?当我们在技术上仍处于__init__循环并且尚未退出时,我对death下的play(self): while True被重新分配到death感到困惑。我想我对于返回{{1}}的位置感到困惑。

2 个答案:

答案 0 :(得分:3)

self.start永远不会被重新分配。第49行的返回值不会返回play()方法的开头,而是返回

next_room_name = room()

next_room_name = self.start根本不在while循环中,因此它在第一次之后永远不会发生。 next_room_name只设置为death,因为这是central_corridor方法返回的内容。

答案 1 :(得分:3)

让我们逐步完成它的几个步骤,直到while循环:

a_game = Game("central_corridor")
a_game.play()

在这里,我们使用a_game = start_value来实例化central_corridor。到目前为止,非常好:)现在我们运行a_game.play()

def play(self):
    next_room_name = self.start

    while True:
        print "\n--------"
        room = getattr(self, next_room_name)
        next_room_name = room()

正如您所说,next_room_name被赋值为central_corridor,然后while循环开始。

这可能是获得的重要部分 - while循环仅执行while部分,并且在其下方缩进的所有内容 - next_room_name 重新分配给每次self.start。相反,我们将room定义为属性next_room_name(即central_corridor),然后运行相同名称的方法。然后在下一个循环中使用该方法的返回值(让我们说death),这意味着room = deathnext_room_name= death()的结果,打印随机的quip然后退出。如果名称是另一个房间,它将继续循环。