我想用一个指定的参数包装一个函数,比如functools.partial,但是它没有按预期工作:
source_codes = (0, 1, 2)
def callback(source, *args):
print 'callback from source: ', source
funcs = []
for source in source_codes:
funcs.append(lambda *args: callback(source, *args))
for i, func in enumerate(funcs):
print 'source expected: ', i
func()
print
Run Code Online (Sandbox Code Playgroud)
输出:
source expected: 0
callback from source: 2
source expected: 1
callback from source: 2
source expected: 2
callback from source: 2
Run Code Online (Sandbox Code Playgroud)
但是......我想要的是:
source expected: 0
callback from source: 0
source expected: 1
callback from source: 1
source expected: 2
callback from source: 2
Run Code Online (Sandbox Code Playgroud)
我知道如果我使用它会有效functools.partial,但我想知道我的代码中的真正问题... lambda包装器是否使用全局变量source?
代码中的问题是 lambda 表达式在被调用之前不会被求值。
然后当它被调用时,它使用 的最新值source。source它在创建 lambda 时不会绑定 的值。
显示此行为的示例代码 -
>>> y = lambda: z
>>> z = 0
>>> y()
0
>>> z = 1
>>> y()
1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |