python之在匿名函数中绑定变量的值

In [17]: [x(2) for x in mu()]
Out[17]: [0, 2, 4, 6]

In [18]: x = 10

In [19]: a = lambda y: x + y

In [20]: x = 20

In [21]: b = lambda y: x + y

In [22]: a(10)
Out[22]: 30

In [23]: b(10)
Out[23]: 30

# lambda表达式中用到的x是一个自由变量,在运行进才进行绑定而不是定义的时候进行绑定。因此,lambda表达式中的x是在执行的时候确定的。

再来看这么一个例子:

In [27]: def multipliers():
    ...:     return [lambda x: i*x for i in range(4)]
In [28 print([m(2) for m in multipliers()])
[6, 6, 6, 6]

# 因为i值是在运行的时候确定的,当调用lambda函数时,for循环已经结束,所以i都是3


# 可以把添加一个默认参数绑定变量,默认值只会函数定义的时候初始化一次
In [33]: def multipliers():
    ...:     return [lambda x, i=i: i*x for i in range(4)]
    ...:
    ...:

In [34]: print([m(2) for m in multipliers()])
[0, 2, 4, 6]

# 或者可以通过如下方式实现
In [16]: from functools import partial
In [17]: from operator import mul
In [35]: def multipliers():
    ...:     return [partial(mul, i) for i in range(4)]
    ...:
    ...:

In [36]: print([m(2) for m in multipliers()])
[0, 2, 4, 6]

Ref:
1.python cookbook