Scope of lambda functions and their parameters?

后端 未结 10 1079
隐瞒了意图╮
隐瞒了意图╮ 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:49

    The problem here is the m variable (a reference) being taken from the surrounding scope. Only parameters are held in the lambda scope.

    To solve this you have to create another scope for lambda:

    def callback(msg):
        print msg
    
    def callback_factory(m):
        return lambda: callback(m)
    
    funcList=[]
    for m in ('do', 're', 'mi'):
        funcList.append(callback_factory(m))
    for f in funcList:
        f()
    

    In the example above, lambda also uses the surounding scope to find m, but this time it's callback_factory scope which is created once per every callback_factory call.

    Or with functools.partial:

    from functools import partial
    
    def callback(msg):
        print msg
    
    funcList=[partial(callback, m) for m in ('do', 're', 'mi')]
    for f in funcList:
        f()
    

提交回复
热议问题