Python 嵌套函数

Python nested function

我发现了这个有趣的代码

# Define echo
def echo(n):
    """Return the inner_echo function."""

    # Define inner_echo
    def inner_echo(word1):
        """Concatenate n copies of word1."""
        echo_word = word1 * n
        return echo_word

    # Return inner_echo
    return inner_echo


# Call echo: twice
twice = echo(2)

# Call echo: thrice
thrice = echo(3)

# Call twice() and thrice() then print
print(twice('hello'), thrice('hello'))

输出:

hellohello hellohellohello

但我无法理解它是如何工作的,因为 两次和三次函数 正在调用函数 echo 并提供value n,word1的value是如何传递的?

echo 函数 return 是另一个函数,n 设置为您传递给它的任何值。当您调用 inner_echo(即 echo 的 return)时,它会保留创建时给定的范围。

在您的示例中,twice 是使用 echo(2) 创建的,其中 return 是 inner_echo 函数,在其范围内,n 设置为2.

同样,由 echo(3) 创建的 thrice 创建了 inner_echonew 版本,其中 n 设置为3.

还记得 echo return 是一个函数吗?当您调用 twicethrice 时,您正在调用 echo returned 的函数 - 即,您没有调用 echo 完全没有。因此,调用 twice 就是调用 inner_echo,这就是 word 的填充方式。

当您在 twice = echo(2) 中使用值 2 调用 echo 时,它会在内部存储值 2。所以当我们调用两次('hello')时,它会记住 n 的值并多次打印它。 当您将 3 传递给与 thrice = echo(3) 相同的函数时,它会在内部存储值 3。

所以,基本上它是创建具有不同 n 值的实例。我希望你明白。

尝试传递它 twice = echo(2) 然后 twice = echo(3) ,在这种情况下它将更新n 的值。

echo 是一个接受参数 n 和 returns 的函数,另一个函数关闭 n 的提供值并接受参数 word1.

换句话说,为某些 n returns 调用 echo(n) 一个函数,然后用 twice(word1)

调用该函数

流量本质上是

echo = function (n) -> function (word1) with closure (n) -> word1 repeated n times

twice = echo (2) -> function (word1) with closure (n = 2) -> word1 repeated 2 times

twice('hello') -> 'hello' repeated 2 times

我用上面的方式描述了它,因为 AFAICT Python 没有表达函数类型的语法。

上面的例子是函数闭包的例子

你最好参考这个linkFunction Closure In Python