One way is to do this:
def main():
files = [r'C:\_localest.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]()
Otherwise f
is looked up when the function is called, so you get the current (after the loop) value.
Ways I like better:
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))
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))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…