Scope of lambda functions and their parameters?

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

    Yes, that's a problem of scope, it binds to the outer m, whether you are using a lambda or a local function. Instead, use a functor:

    class Func1(object):
        def __init__(self, callback, message):
            self.callback = callback
            self.message = message
        def __call__(self):
            return self.callback(self.message)
    funcList.append(Func1(callback, m))
    

提交回复
热议问题