【发布时间】:2018-05-10 06:59:02
【问题描述】:
我遇到了这个有趣的代码
# 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'))
输出:
你好你好你好你好
但我无法理解它是如何工作的,因为 两次和三次函数 正在调用函数 echo 并提供 值 n,word1的值是怎么传递的?
【问题讨论】:
-
第一个 echo 函数被初始化,如果你已经熟悉 class,就和 class 一样。这个构造类似于你初始化主函数,而不是你可以将值传递给内部方法。例如。在 JavaScript 中没有合适的类(没有创建像 String 这样的新类型)——它们实际上是包含其他函数的函数。
-
您正在查看的内容称为闭包。当我第一次遇到这个概念时,我很难理解它,但是一旦你知道了这个词,你就可以搜索它并阅读一些东西来获得理解。很多语言都有它们,这里有一个链接可以很好地解释它。:stackoverflow.com/a/7464475/1468125
标签: python python-3.x nested-function