[Tutor] Minesweeper the return

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Wed Jul 20 01:18:09 CEST 2005


Quoting Alberto Troiano <albertito_g at hotmail.com>:

> Please let's talk about this more! *grin*
> I'm not sure if I'm following you, what I see here is a function inside
> other function and the first function returns its inside function, but
> how does it work?

In Python, as in other modern languages, functions are "first-class" objects. 
In particular, you can pass functions as arguments to other functions, or return
functions from other functions.

I like examples:

>>> def add(x, y):
...  return x + y
...
>>> f = add          # Notice the lack of brackets after 'add'
>>> f(3, 5)
8
>>> f(9, 12)
21

In this case, all I've done is assigned to f the function 'add'.  This means
that f is now a function, and I can call it, even though I never did 'def f(x,
y)' anywhere.

>>> def square(x):
...  return x*x
...
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> map(square, range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The 'map' builtin function takes two arguments: a function and a list.  It makes
a new list by applying the function to each element of the old list.
ie: This is an example of passing a functino as an argument.

Finally:

>>> def makeAdder(x):
...  def add(y):
...   return x + y
...  return add
...
>>> f = makeAdder(5)
>>> f(3)
8
>>> f(8)
13

'def add(y)' defines a function of one argument, which adds that argument to x,
and returns the result.  What is x? Well, x is a variable in the scope of
makeAdder(); it gets bound to the argument you pass.  In my example, x was bound
to 5.  So, effectively, we have created a new function by: 'def add(y): return 5
+ y', and then returned that function to f.  We can now call f and see the result.

HTH!

-- 
John.

[ps: sorry for the troll.. I couldn't resist :-) ]


More information about the Tutor mailing list