很难理解嵌套函数
Having a hard time understanding nested functions
python 新手,我目前正在学习 python 中的嵌套函数。我很难理解下面示例中的代码。特别是,在脚本的底部,当您打印 echo(2)("hello")
时 - inner_function 如何知道将字符串 "hello"
作为其参数输入?在我看来,我认为您必须将字符串作为某种输入传递给外部函数 (echo
)?只需将字符串放在与外部函数调用相邻的括号中就可以了?我似乎无法解决这个问题..
-有抱负的pythonista
# 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 twice() and thrice() then print
print(echo(2)('hello'), echo(3)('hello'))
这里重要的是,在 Python 中,函数本身也是对象。函数可以 return 任何类型的对象,因此函数原则上也可以 return 函数。这就是 echo
所做的。
因此,您的函数调用 echo(2)
的输出又是一个函数,并且 echo(2)("hello")
计算该函数 - 使用 "hello"
作为输入参数。
如果将该调用分成两行,也许更容易理解该概念:
my_function_object = echo(2) # creates a new function
my_function_object("hello") # call that new function
编辑
也许这样更清楚:如果你拼出一个没有括号的函数名,你就是在把这个函数当作一个对象来处理。例如,
x = numpy.sqrt(4) # x is a number
y = numpy.sqrt # y is a function object
z = y(4) # z is a number
接下来,如果您查看 echo
函数中的语句 return echo_word
,您会注意到 returned 的是内部函数(没有任何括号)。所以它是一个由 echo
编辑的函数对象 return。您也可以使用 print(echo(2))
检查
python 新手,我目前正在学习 python 中的嵌套函数。我很难理解下面示例中的代码。特别是,在脚本的底部,当您打印 echo(2)("hello")
时 - inner_function 如何知道将字符串 "hello"
作为其参数输入?在我看来,我认为您必须将字符串作为某种输入传递给外部函数 (echo
)?只需将字符串放在与外部函数调用相邻的括号中就可以了?我似乎无法解决这个问题..
-有抱负的pythonista
# 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 twice() and thrice() then print
print(echo(2)('hello'), echo(3)('hello'))
这里重要的是,在 Python 中,函数本身也是对象。函数可以 return 任何类型的对象,因此函数原则上也可以 return 函数。这就是 echo
所做的。
因此,您的函数调用 echo(2)
的输出又是一个函数,并且 echo(2)("hello")
计算该函数 - 使用 "hello"
作为输入参数。
如果将该调用分成两行,也许更容易理解该概念:
my_function_object = echo(2) # creates a new function
my_function_object("hello") # call that new function
编辑
也许这样更清楚:如果你拼出一个没有括号的函数名,你就是在把这个函数当作一个对象来处理。例如,
x = numpy.sqrt(4) # x is a number
y = numpy.sqrt # y is a function object
z = y(4) # z is a number
接下来,如果您查看 echo
函数中的语句 return echo_word
,您会注意到 returned 的是内部函数(没有任何括号)。所以它是一个由 echo
编辑的函数对象 return。您也可以使用 print(echo(2))