Simple Function Question

Gordon McMillan gmcm at hypernet.com
Wed Apr 26 15:27:23 EDT 2000


Akira Kiyomiya wrote:

> Hi,  Could you explain this in dummy's language?
[snip]
> # Return a function that returns its argument incremented by 'n'
> def make_incrementer(n):
>     def increment(x, n=n):
>         return x+n
>     return increment
> 
> add1 = make_incrementer(1)
> print add1(3)  # This prints '4'

When you call make_increment, the inner "def" is executed; 
(the "def" for make_increment was executed once, when the 
module / script was first loaded). The inner "def" uses a 
default argument (evaluated when make_increment is called) 
to store the value of n in the newly created function object.

If you execute add2 = make_increment(2), you'll find that 
add1.__name__ and add2.__name__ are both "increment", 
but they are different function objects, and the name 
"increment" is actually a local name to make_increment, (it 
doesn't make it to the global namespace).

- Gordon




More information about the Python-list mailing list