gpt4 book ai didi

Python嵌套函数

转载 作者:行者123 更新时间:2023-11-28 17:10:57 25 4
gpt4 key购买 nike

我遇到了这个有趣的代码

# 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并提供值nword1的值是如何传递的?

最佳答案

echo 是一个函数,它接受一个参数 n 并返回另一个函数,该函数关闭 n 的提供值并且也接受一个参数word1.

换句话说,为一些 n 调用 echo(n) 返回一个函数,然后用 twice(word1) 调用该函数p>

流量本质上是。

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 没有用于表达函数类型的语法。

关于Python嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47504144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com