I was reading this page and I found the following example code in the Python documentation, but I don't fully understand how the result is produced.
Example:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
What I don't fully understand is how the number 42 gets increased to 43 when x
isn't set inside the function.
From my understanding every call to f
is like calling a new instance of the method, but it doesn't behave that way.
Questions:
- Why is the first call to
f
done like this:f = make_incrementor(42)
but the other calls aren't ? - How does
x
get set so that every number passed to the function as an argument gets added to it?