lambda function returning false

2019-05-24 20:45发布

问题:

I have a python program in pyqt with a button with the follwoing:

this=[1,k]   
button.clicked.connect(lambda x=this:self.testFunction(str(x)))

When I press the button I get testFunction(False) rather testFunction(str([1,k])). Any ideas why? Thanks in advance.

回答1:

The reason is that you are misinterpretting how lambda works. Lambda returns an anonymous function with the definition you give it. By saying lambda x=this: you are saying if the call to this function doesn't have an x argument default to use this instead.

Observe:

l = lambda x=3: x*2
print l(10)  # Prints 20
print l()    # Prints 6

If we check the documentation for QPushButton.clicked() (inherited from QAbstractButton), we see that it fires with a boolean argument.

So in this line:

button.clicked.connect(lambda x=this:self.testFunction(str(x)))

The lambda function always gets passed an argument, which is passed from QPushButton.clicked() and will be either True or False. Hence the default of this is never used. As an alternate you could use:

button.clicked.connect(lambda x:self.testFunction(str(this)))

But that isn't probably what you want, as it will always pass the string variant of the array this to the function. On the other hand this:

button.clicked.connect(lambda x:self.testFunction(str(this[x])))

Will pass the string casting of their 1 or k depending on whether the passed argument is True or False.