【发布时间】:2016-07-27 14:04:08
【问题描述】:
我有 C++ 背景,正在尝试学习一些 python。
虽然我了解 C++ 的虚函数,但遗憾的是我不明白 python 中闭包的后期绑定是什么意思。
链接:https://gist.github.com/deemson/8efabf56d67623ead804(不再有效)
从教程复制粘贴:
functions = []
for n in [1, 2, 3]:
def func(x):
return n*x
functions.append(func)
# You would expect this to print [2, 4, 6]
print(
'calling a list of bad closures and output is: {}'
.format(str([function(2) for function in functions]))
)
这里到底发生了什么?当函数附加到列表中时,它有什么值?有人可以简化这段代码让我理解吗?
【问题讨论】: