lambda 中的变量作用域 [英] Variable scope inside lambda

查看:41
本文介绍了lambda 中的变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码打印的是d, d, d, d",而不是a, b, c, d"?如何修改它以打印a、b、c、d"?

Why does this code print "d, d, d, d", and not "a, b, c, d"? How can I modify it to print "a, b, c, d"?

cons = []
for i in ['a', 'b', 'c', 'd']: 
    cons.append(lambda: i)  
print ', '.join([fn() for fn in cons])      

推荐答案

奇怪的是,这不是变量作用域的问题,而是python的for 循环(以及 python 的变量).

Oddly enough, this is not a variable scope problem, but a quesiton of the semantics of python's for loop (and of python's variables).

如您所料,lambda 中的 i 正确地引用了最近的封闭作用域中的变量 i.到目前为止,一切都很好.

As you expect, i inside your lambda correctly refers to the variable i in the nearest enclosing scope. So far, so good.

但是,您希望这意味着以下情况发生:

However, you are expecting this to mean the following happens:

for each value in the list ['a', 'b', 'c', 'd']: 
    instantiate a new variable, i, pointing to the current list member
    instantiate a new anonymous function, which returns i
    append this function to cons

实际发生的事情是这样的:

What actually happens is this:

instantiate a new variable i
for each value in the list ['a', 'b', 'c', 'd']: 
    make i refer to the current list member
    instantiate a new anonymous function, which returns i
    append this function to cons

因此,您的代码将 same 变量 i 附加到列表四次——当循环退出时,i具有 'd' 的值.

Thus, your code is appending the same variable i to the list four times -- and by the time the loop exits, i has a value of 'd'.

请注意,如果python函数通过value获取并返回其参数的值/返回值,您不会注意到这一点,因为i的contents 将在每次调用 append 时被复制(或者,就此而言,在每次从使用 lambda 创建的匿名函数返回时).然而,实际上,python 变量总是引用到一个特定的对象——因此你的 i 的四个副本都引用了 'd'到那时你的循环结束.

Note that if python functions took and returned the value of their arguments / return values by value, you would not notice this, as the contents of i would be copied on each call to append (or, for that matter, on each return from the anonymous function created with lambda). In actuality, however, python variables are always references to a particular object-- and thus your four copies of i all refer to 'd' by then end of your loop.

这篇关于lambda 中的变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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