Lambda函数和变量范围 [英] Lambda function and variable scope

查看:87
本文介绍了Lambda函数和变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我的代码如下:

for control in self.controls():
  self.connect(control, SIGNAL('clicked()'), lambda: self.button(control.objectName()))

运行代码时,我的lambda函数将control用作元素列表中的 last 元素,这不是我期望的.

When I run my code, my lambda function takes control to be the last element in my list of elements, which is not what I expect to happen.

奇怪的是,当我手动运行每个循环的lambda时,它在每个循环中都可以正常工作,但是最后仍然存在与以前相同的问题:

Oddly enough, when I manually run the lambda every loop, it works fine for each loop, but it still has the same problem as before in the end:

for control in self.controls():
  func = lambda: self.button(control.objectName())
  func() # Prints the correct output

  self.connect(control, SIGNAL('clicked()'), func) # When triggered, still breaks

我的self.button()函数是简单定义的:

My self.button() function is trivially defined:

def button(self, name):
    print name

我通过打印id(control)id(func)的输出来检查每个循环中controlfunc的唯一性,它们都返回了唯一的数字.除此之外,control.objectName()是正确的对象名称.

I checked for the uniqueness of control and func every loop by printing the output of id(control) and id(func) and they all returned unique numbers. Aside from that, control.objectName() is the correct object name.

我感觉这是一个变量范围问题,因为我通常在代码中不经常使用lambda.有人看到任何公然的错误吗?

I have a feeling that this is a variable scope problem, as I usually don't use lambdas too often in my code. Does anybody see any blatant mistakes?

推荐答案

SPLAT.

for control in self.controls():
  self.connect(control, SIGNAL('clicked()'), lambda control=control:
    self.button(control.objectName()))

这篇关于Lambda函数和变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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