Scope of lambda functions and their parameters?

后端 未结 10 1074
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:22

I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it.

10条回答
  •  独厮守ぢ
    2020-11-22 13:29

    The variable m is being captured, so your lambda expression always sees its "current" value.

    If you need to effectively capture the value at a moment in time, write a function takes the value you want as a parameter, and returns a lambda expression. At that point, the lambda will capture the parameter's value, which won't change when you call the function multiple times:

    def callback(msg):
        print msg
    
    def createCallback(msg):
        return lambda: callback(msg)
    
    #creating a list of function handles with an iterator
    funcList=[]
    for m in ('do', 're', 'mi'):
        funcList.append(createCallback(m))
    for f in funcList:
        f()
    

    Output:

    do
    re
    mi
    

提交回复
热议问题