在学习Berkeley的CS61a---即structure and interpretation of computer program课程的时候,碰到一个作业
里面用到了嵌套的函数,跟函数调用时生成的框架相关
函数的目的时输出一个游戏玩家的得分情况,如果单轮游戏的得分超过了以往的最高单轮游戏得分,那么将会输出一句评论,说明本轮的得分情况。这里面牵涉到了用previous_score即上轮得分 和 previous_high前面单轮最高得分,作为参数调用一个函数,并在这个函数announce_highest中生成另外一个函数say_highest,以本轮得分作为输入参数,检查是否满足评论条件,以决定是否发表评论。
这是原始代码:
def announce_highest(who, previous_high=0, previous_score=0):
"""Return a commentary function that announces when WHO's score
increases by more than ever before in the game.
>>> f0 = announce_highest(1) # Only announce Player 1 score gains
>>> f1 = f0(11, 0)
>>> f2 = f1(11, 1)
1 point! That's the biggest gain yet for Player 1
>>> f3 = f2(20, 1)
>>> f4 = f3(5, 20) # Player 1 gets 4 points, then Swine Swap applies