python闭包变量迟邦定

时间:2022-07-05 22:48:26

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]