如何理解lambda中的闭包? [英] How to understand closure in a lambda?

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

问题描述

我想循环制作5个按钮,并为每个按钮绑定一条命令以打印索引.在以下解决方案中,它始终打印相同的索引.

I want to make 5 buttons in a loop, and for each buttons bind a commend to print the index. In the following solution it always prints the same index.

我的代码如下:

for i in range(5):
    make_button = Tkinter.Button(frame, text ="make!", 
                                 command= lambda: makeId(i))

def makeId(i):
    print(i)

它总是打印5.如何解决此问题?

It always prints 5. How can I fix this?

推荐答案

执行lambda时,将完成lambdas中变量的解析.此时,对于所有按钮,i = 5.要纠正此问题,请执行以下操作:

Resolution of variables in lambdas is done when lambda is executed. At this time, for all buttons i=5. To rectify this issue do as follows:

 make_button = Tkinter.Button(frame, text ="make!", 
                              command= lambda i=i: makeId(i))

这会将i创建为lambda中的局部变量.此局部变量将从循环中保存i的正确值.局部变量可以具有任何名称,不一定是i,例如command= lambda a=i: makeId(a)).

This creates i as a local variable in a lambda. This local variable will hold correct value of i from the loop. the local variable can have any name, not necessarily i, e.g. command= lambda a=i: makeId(a)).

这篇关于如何理解lambda中的闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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