python闭包变量迟邦定

python闭包变量迟绑定

>>> def foo():
...     return [lambda x: i * x for i in range(4)]
...
>>> print([m(3) for m in foo()])
[9, 9, 9, 9]

# 等价于

>>> def foo():
...     l = []
...     for i in range(4):
...         def wrapper(x):
...             return i * x
...         l.append(wrapper)
...     return l
...
>>> print [m(3) for m in foo()]
[9, 9, 9, 9]


# 想得到预期的做法

>>> def foo():
...     return [lambda x, i = i: i * x for i in range(4)]
...
>>> print [m(3) for m in foo()]
[0, 3, 6, 9]

# 等价于
>>> def foo():
...     l = []
...     for i in range(4):
...         def wrapper(x, i=i):
...             return i * x
...         l.append(wrapper)
...     return l
...
>>>
>>> print [m(3) for m in foo()]
[0, 3, 6, 9]
原文地址:https://www.cnblogs.com/fzw-/p/8325788.html