Simple Function Question
wware at world.std.com
Wed Apr 26 21:28:42 CEST 2000
Akira Kiyomiya (akira.kiyomiya at autodesk.com) wrote:
> This function prints out '4' and I have a feeling that x=1 and n=3, so
> add1(3) prints '4'.
> However, I have a difficlut time trying to see how these two arguments
> assigned to both x (especially x) and 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 run make_incrementer(1), let's see what happens. You've given
it an argument of 1, which is given the name 'n' inside the body of
make_incrementer. Within that body, you come to 'def increment...'
which, as you know, defines a function. The notation 'n=n' means that
increment can be called with either one argument or with two arguments,
and if it's called with one argument, then its second argument will
assume a default value. That value is 'n' (taken from its value within
the body of make_incrementer), so when you later say 'make_incrementer(1)'
that default value becomes 1. The next thing that happens is that
make_incrementer returns this function; in Python, functions are
objects that can be passed or returned, just like numbers, strings,
lists, dictionaries, or class instances. So this function is given
the name 'add1'. When you call 'add1(3)', the function (originally
called incrementer, and with 1 as the default value for its second
argument) takes 3 as the first argument, adds its two arguments, and
returns the sum (4) which gets printed.
The first tricky idea here is that functions can be passed like any
other object. You'll be familiar with this if you've used Lisp or
Scheme, or Postscript, and probably other languages that escape me now.
In C, a function is pretty tightly connected to its original name; you
can pass pointers to functions but not the function itself. And the
only way to hide the name is to declare the function static, and then
it's only hidden outside that particular source file.
The second tricky idea is that functions' arguments can have default
values, which are set when the 'def' happens and don't change after
that. This allows you to hide all kinds of useful information in an
anonymous function, or create multiple instances of the function with
different default arguments. A default argument can be another function,
possibly with its own default arguments.
I hope this helps.
- - - - - - - - - - - - - - - - - - - - - - - -
Resistance is futile. Capacitance is efficacious.
Will Ware email: wware @ world.std.com
More information about the Python-list