Scope of lambda functions and their parameters?

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

    First, what you are seeing is not a problem, and not related to call-by-reference or by-value.

    The lambda syntax you defined has no parameters, and as such, the scope you are seeing with parameter m is external to the lambda function. This is why you are seeing these results.

    Lambda syntax, in your example is not necessary, and you would rather be using a simple function call:

    for m in ('do', 're', 'mi'):
        callback(m)
    

    Again, you should be very precise about what lambda parameters you are using and where exactly their scope begins and ends.

    As a side note, regarding parameter passing. Parameters in python are always references to objects. To quote Alex Martelli:

    The terminology problem may be due to the fact that, in python, the value of a name is a reference to an object. So, you always pass the value (no implicit copying), and that value is always a reference. [...] Now if you want to coin a name for that, such as "by object reference", "by uncopied value", or whatever, be my guest. Trying to reuse terminology that is more generally applied to languages where "variables are boxes" to a language where "variables are post-it tags" is, IMHO, more likely to confuse than to help.

提交回复
热议问题