Python 闭包未按预期工作 [英] Python closure not working as expected
本文介绍了Python 闭包未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行以下脚本时,两个 lambda 都在同一个文件——junk.txt 上运行 os.startfile().我希望每个 lambda 都使用创建 lambda 时设置的值f".有没有办法让它按照我的预期运行?
When I run the following script, both lambda's run os.startfile() on the same file -- junk.txt. I would expect each lambda to use the value "f" was set to when the lambda was created. Is there a way to get this to function as I expect?
import os
def main():
files = [r'C:\_local est.txt', r'C:\_localjunk.txt']
funcs = []
for f in files:
funcs.append(lambda: os.startfile(f))
print funcs
funcs[0]()
funcs[1]()
if __name__ == '__main__':
main()
推荐答案
一种方法是:
def main():
files = [r'C:\_local est.txt', r'C:\_localjunk.txt']
funcs = []
for f in files:
# create a new lambda and store the current `f` as default to `path`
funcs.append(lambda path=f: os.stat(path))
print funcs
# calling the lambda without a parameter uses the default value
funcs[0]()
funcs[1]()
否则 f
在函数被调用时被查找,所以你得到当前(循环后)值.
Otherwise f
is looked up when the function is called, so you get the current (after the loop) value.
我更喜欢的方式:
def make_statfunc(f):
return lambda: os.stat(f)
for f in files:
# pass the current f to another function
funcs.append(make_statfunc(f))
甚至(在python 2.5+中):
or even (in python 2.5+):
from functools import partial
for f in files:
# create a partially applied function
funcs.append(partial(os.stat, f))
这篇关于Python 闭包未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文