How does a lambda function refer to its parameters in python?

前端 未结 4 1744
余生分开走
余生分开走 2021-01-05 17:09

I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like

fs = [         


        
4条回答
  •  甜味超标
    2021-01-05 17:42

    The problem you are running into here is the distinction between "early binding" and "late binding".

    When Python looks up a variable from an outer scope (i in this case) it uses late binding. That means it sees the value of that variable at the time the function is called, rather than the value at the time the function is defined.

    So, in your example code, all 10 lambda functions see the final value assigned to the i variable by the looping process: 9.

    Greg's answer shows one way to force early binding behaviour (i.e. create an additional closure and call it immediately while still inside the loop).

    Another commonly used approach to forcing early binding semantics is the "default argument hack", which binds the variable as a default argument at function definition time:

    >>> fs = [(lambda x, _i=i: x + _i) for i in xrange(10)]
    >>> [f(0) for f in fs]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Either method works. Greg's has the advantage of not messing with the returned function's signature, the default argument hack is faster and is significantly more readable than adding an additional closure level when defining named functions rather than using lambda expressions.

提交回复
热议问题