Python闭包不能按预期工作 [英] Python closure not working as expected

查看:88
本文介绍了Python闭包不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的脚本,两个lambda的运行os.startfile()在同一个文件 - junk.txt。我期望每个lambda使用的值f设置为创建lambda时。是否有办法让我的预期功能?

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\test.txt', r'C:\_local\junk.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\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 (循环后)值。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆