312 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
the function in foo to the variable bar. This means we can call bar() just like we can call
foo()! Note that in this assignment statement we do not have parentheses after foo. If we did,
we would be calling the function foo() and setting bar to its return value. Just like spam[42]
has the [42] index operating on spam, the parentheses means, “Call the value in foo as a
function.”
You can also pass functions as values just like any other value. Try typing the following into the
interactive shell:
def doMath(func):
... return func(10, 5)
...
def adding(a, b):
... return a + b
...
def subtracting(a, b):
... return a - b
...
doMath(adding)
15
doMath(subtracting)
5
When the function in adding is passed to the doMath() call, the func(10, 5) line is
calling adding() and passing 10 and 5 to it. So the call func(10, 5) is effectively the
same as the call adding(10, 5). This is why doMath(adding) returns 15.
When subtracting is passed to the doMath() call, func(10, 5) is the same as
subtracting(10, 5). This is why doMath(subtracting) returns 5.
Passing a function or method to a function or method call is how the sort() method lets you
implement different sorting behavior. The function or method that is passed to sort() should
accept a single parameter and returns a value that is used to alphabetically sort the item.
To put it another way: normally sort() sorts the values in a list by the alphabetical order of the
list values.. But if we pass a function (or method) for the key keyword argument, then the values
in the list are sorted by the alphabetical or numeric order of the return value of the function when
the value in the list is passed to that function.
You can think of a normal sort() call such as this: