Lambda function and variable scope

此生再无相见时 提交于 2019-12-23 12:13:17

问题


Currently, my code is like this:

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

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.

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

My self.button() function is trivially defined:

def button(self, name):
    print name

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.

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?


回答1:


SPLAT.

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


来源:https://stackoverflow.com/questions/10611461/lambda-function-and-variable-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!