[Tutor] Minesweeper the return

Alberto Troiano albertito_g at hotmail.com
Wed Jul 20 14:58:34 CEST 2005


I think I got it......finally.......*grin*
I will try to put this in practice right away and let you know if I have so 
more problems or if I didn't understand what I think I did.

jeje

Thank you Jhon and Danny

Best Regards,

Alberto

>From: jfouhy at paradise.net.nz
>To: "tutor at python.org" <tutor at python.org>
>Subject: Re: [Tutor] Minesweeper the return
>Date: Wed, 20 Jul 2005 11:18:09 +1200 (NZST)
>
>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 :-) ]
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor


Gaucho




More information about the Tutor mailing list