如何强制Python在循环内创建新变量/新作用域? [英] How can I force Python to create a new variable / new scope inside a loop?

查看:89
本文介绍了如何强制Python在循环内创建新变量/新作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我探讨了Python的奇怪行为.一个例子:

Today I explored a weird behavior of Python. An example:

closures = []
for x in [1, 2, 3]:
    # store `x' in a "new" local variable
    var = x

    # store a closure which returns the value of `var'
    closures.append(lambda: var)

for c in closures:
    print(c())

上面的代码打印

3
3
3

但是我希望它打印

1
2
3

我为我自己解释了这种行为,即var始终是相同的局部变量(并且python不会像其他语言那样创建新的局部变量).如何修复上面的代码,以便每个闭包都将返回另一个值?

I explain this behavior for myself that var is always the same local variable (and python does not create a new one like in other languages). How can I fix the above code, so that each closure will return another value?

推荐答案

最简单的方法是为lambda使用默认参数,这种方式将x的当前值绑定为函数,而不是在每次调用的包含范围中查找var:

The easiest way to do this is to use a default argument for your lambda, this way the current value of x is bound as the default argument of the function, instead of var being looked up in a containing scope on each call:

closures = []
for x in [1, 2, 3]:
    closures.append(lambda var=x: var)

for c in closures:
    print(c())

或者,您可以创建一个闭包(因为闭包是在全局范围内创建的,所以您不是闭包):

Alternatively you can create a closure (what you have is not a closure, since each function is created in the global scope):

make_closure = lambda var: lambda: var
closures = []
for x in [1, 2, 3]:
    closures.append(make_closure(x))

for c in closures:
    print(c())

make_closure()也可以这样写,这可能使其更具可读性:

make_closure() could also be written like this, which may make it more readable:

def make_closure(var):
    return lambda: var

这篇关于如何强制Python在循环内创建新变量/新作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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