Reputation:
I am a c++ guy, learning the lambda function in python and wanna know it inside out. did some seraches before posting here. anyway, this piece of code came up to me.
<1> i dont quite understand the purpose of lambda function here. r we trying to get a function template? If so, why dont we just set up 2 parameters in the function input?
<2> also, make_incrementor(42)
, at this moment is equivalent to return x+42
, and x is the 0
,1
in f(0)
and f(1)
?
<3> for f(0)
, does it not have the same effect as >>>f = make_incrementor(42)
? for f(0)
, what are the values for x
and n
respectively?
any commments are welcome! thanks.
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
Upvotes: 0
Views: 162
Reputation: 6317
Yes, this is similar to a C++ int
template. However, instead of at compile time (yes, Python (at least for CPython) is "compiled"), the function is created at run time. Why the lambda is used in this specific case is unclear, probably only for demonstration that functions can be returned from other functions rather than practical use. Sometimes, however, statements like this may be necessary if you need a function taking a specified number of arguments (e.g. for map
, the function must take the same number of arguments as the number of iterables given to map
) but the behaviour of the function should depend on other arguments.
make_incrementor
returns a function that adds n
(here, 42
) to any x
passed to that function. In your case the x
values you tried are 0
and `1``
f = make_incrementor(42)
sets f
to a function that returns x + 42
. f(0)
, however, returns 0 + 42
, which is 42
- the returned types and values are both different, so the different expressions don't have the same effect.
Upvotes: 1
Reputation: 1259
The purpose is to show a toy lambda return. It lets you create a function with data baked in. I have used this less trivial example of a similar use.
def startsWithFunc(testString):
return lambda x: x.find(testString) == 0
Then when I am parsing, I create some functions:
startsDesctription = startsWithFunc("!Sample_description")
startMatrix = startsWithFunc("!series_matrix_table_begin")
Then in code I use:
while line:
#.... other stuff
if startsDesctription(line):
#do description work
if startMatrix(line):
#do matrix start work
#other stuff ... increment line ... etc
Still perhaps trival, but it shows creating general funcitons with data baked it.
Upvotes: 1