<分区>
我有 C++ 背景,正在尝试学习一些 python。
虽然我了解 C++ 的虚函数,但不幸的是我不明白 python 中闭包的后期绑定(bind)是什么意思。
链接: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]))
)
这里究竟发生了什么?当函数附加到列表中时,它有什么值?有人可以简化这段代码以便我理解吗?