【问题标题】:Conceptual understanding of variable scope in higher order functions高阶函数中变量作用域的概念理解
【发布时间】:2021-12-11 09:07:57
【问题描述】:

我有一个函数score0,它给我一个循环中的每一圈(n 圈)的分数。这个分数每回合增加一个从 1 到 15 的随机整数。

我现在必须设计另一个更高阶的函数,它应该打印玩家在所有得分跳跃中的最高得分跳跃,并且应该在score0 函数中调用。我把它命名为highest_gain。当然,这应该打印第一个得分值,因为它是第一轮(因此它是最大的跳跃)。

# Function that defines the highest point jump in a score yet
import random
def highest_gain(previous_value, highest_point):
    def say(score) :
        if previous_value == 0:
            print ('Biggest gain by player0 yet with',score,'points!') 
            return highest_gain(score, score) 
        gain = score - previous_value
        if gain > highest_point:
           print('Biggest gain by player0 yet with',score,'points!') 
           return highest_gain(score, gain)
    return say

# Function that gives me a new score (incremented) every turn    
def score0(n, score = 0):
    while n > 0:
          score += random.randint(1, 15)
          highest_gain(previous_value = 0,highest_point = 0)(score)
          n -= 1
    return score

#Calling the function   
score0(4,0)

Python Tutor link

问题是调用highest_gain() 不会更新previous_valuehighest_point 的值。为什么这些变量没有在 score0() 函数体中更新,应该如何调用 highest_gain() 以便在循环的每次迭代中更新这些变量?

【问题讨论】:

  • 为了清楚起见,您认为变量应该在哪里更新?
  • 应该在score0函数体中更新

标签: python python-3.x higher-order-functions


【解决方案1】:

您的highest_gain 函数是一个高阶函数,它返回另一个名为say 的函数。当say 被调用时,它会再次调用highest_gain 并返回结果,也就是函数say。这里重要的一点是say 是外部函数highest_gain 的局部变量上的closure,所以每次调用highest_gain 你都会得到say 函数的不同实例,具有不同的值外部函数的局部变量。

现在,由于调用 say 返回另一个 say 实例,它关闭了更新的值,这意味着您需要在调用它时保留结果,因此您可以调用关闭那些更新的新实例价值观。

def score0(n, score=0):
    say = highest_gain(previous_value=0, highest_point=0)
    while n > 0:
          score += random.randint(1, 15)
          say = say(score) or say
          n -= 1
    return score

我将highest_gain 的原始调用移到循环之前,因为您不想在每次迭代时都使用0 的初始值。

请注意,say 并不总是返回 say 的新实例 - 有时它会返回 None,所以我在这里使用了技巧 say(score) or say,以便 say 保持如果没有新的值来更新它,它的旧值。你也可以这样写,这样更冗长,但可能更清楚这是做什么的:

new_say = say(score)
if new_say is not None:
    say = new_say

否则,您可以更改 say 的定义,使其在不应更新时返回自身(即使用外部函数的变量的当前值),然后在 score0 中您可以只写say = say(score).

【讨论】:

  • 这非常有帮助!作为一个刚刚开始学习这些东西的人,我不能夸大学习差距有多大,因为这个概念被澄清了。
猜你喜欢
  • 1970-01-01
  • 2014-10-07
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 2014-11-19
相关资源
最近更新 更多