一种方法是执行此操作:
def main():
files = [r'C:\_local\test.txt', r'C:\_local\junk.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
,在调用该函数时将进行查找,因此您将获得当前(循环后)的值。
我更喜欢的方式:
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+中):
from functools import partial
for f in files:
# create a partially applied function
funcs.append(partial(os.stat, f))