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

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

问题描述

我想创建5个按钮,每个按钮绑定一个命令以打印此索引。
,但总是打印5。

I want to make 5 buttons and each buttons bind a commend to print this index. but always print 5.

我的代码就像这样,

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

def makeId(i):
    print(i)

它总是打印5, ?
感谢很多~~

It always print 5 , then how can i do ? thanks a lot~~

推荐答案

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)).

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

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