python, basic lambda function -
i c++ guy, learning lambda function in python , wanna know inside out. did seraches before posting here. anyway, piece of code came me.
<1> dont quite understand purpose of lambda function here. r trying function template? if so, why dont set 2 parameters in function input?
<2> also, make_incrementor(42), @ moment equivalent return x+42, , x 0,1 in f(0) , f(1)?
<3> f(0), not have same effect >>>f = make_incrementor(42)? f(0), values x , n respectively?
any commments welcome! thanks.
>>> def make_incrementor(n): ... return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43
yes, similar c++
inttemplate. however, instead of @ compile time (yes, python (at least cpython) "compiled"), function created @ run time. why lambda used in specific case unclear, demonstration functions can returned other functions rather practical use. sometimes, however, statements may necessary if need function taking specified number of arguments (e.g.map, function must take same number of arguments number of iterables givenmap) behaviour of function should depend on other arguments.make_incrementorreturns function addsn(here,42)xpassed function. in casexvalues tried0, `1``f = make_incrementor(42)setsffunction returnsx + 42.f(0), however, returns0 + 42,42- returned types , values both different, different expressions don't have same effect.
Comments
Post a Comment