Consider the following Python 3 instructions
res = []
for a in range(3) :
res.append(lambda n : n + a)
in order to create a list of resthree functions res[0], res[1]and res[2]such that res[i](n)returns n + ifor all iin [0, 1, 2].
However, it turns out
>>> res[0](0)
2
instead
>>> res[0](0)
0
Also have
>>> res[1](2)
4
The explanation for this behavior is that in the expression n + ain the body of any dynamically generated anonymous function of the example, the symbol is anot evaluated when the function is created. Evaluation is performed when the for statement is exited, explaining why all functions are res[0], res[1]and res[2]return the value of their argument plus 2Γ¨ (becausea browsesrange (3) and2 `is its last value).
, , . ,
res = []
for a in range(3) :
def f(n) :
return n + a
res.append(f)
.
, , , eval Python:
res = []
for a in range(3) :
s = "lambda n : n + %s" %(a)
res.append(eval(s))
, a res.