[Tutor] Python functions are first-class citizens

Alan Gauld alan.gauld at btinternet.com
Fri Aug 1 08:32:22 CEST 2014


On 01/08/14 06:12, memilanuk wrote:

> counts = {'a':1, 'b':22, 'c':100}
>
> then counts.get('b') should return 22.  I got that much.
>
> And counts.get is just an uncalled version of that:
>
> foo = counts.get
> foo('b')
>
> should return 22 as well.  Think I got that as well.

Well done, thats the crux of it.

> Where things are going pear-shaped is how counts.get can function as a
> 'key' when we don't actually supply () (or anything inside them)

The max() function calls the key function internally.

Here is a trivial example (untested code!)

 >>> def f(aFunc):
       for n in range(3):
         print("Your function returns",aFunc(n),"with input",n)
 >>>
 >>> def g(n):
       return n+2
 >>>
 >>> f(g)
Your function returns 2 with input 0
Your function returns 3 with input 1
Your function returns 4 with input 2

So f calls aFunc using n internally.
The specification of f requires that you pass it a function that accepts 
a single argument

max and sort etc work the same way.
They call your function internally.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list