Lambda function and variable scope

2019-06-26 01:49发布

问题:

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