[Tutor] pass a function name as an argument

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 23 Jul 2001 14:41:05 -0700 (PDT)


On Mon, 23 Jul 2001, Peter He wrote:

> How can I pass a function name as an argument to another function?

Here's an example that might help show how to pass functions around:

###
>>> def fixedPoint(func, initial_value):
...     epsilon = 0.01
...     current_value = func(initial_value) 
...     while 1:                    
...         new_value = func(current_value)
...         if abs(new_value - current_value) < epsilon:   
...             break
...         current_value = new_value
...     return current_value
... 
>>> import math
>>> fixedPoint(math.cos, 0)
0.74423735490055687
>>> math.cos(0.74423735490055687)
0.73560474043634738
###

In this example, fixedPoint() is a function that takes other functions as
arguments.  In math terms, it tries to find the "fixed point" of a given
function.  The call here:

    fixedPoint(math.cos, 0)

passes math.cos off to the fixedPoint function.  As long as we don't put
parens like "math.cos()", Python will allow us to pass this function
around like any other variable.


It looks like you're trying to pass the member function of an instance.  
Can you show us an example of what you're doing?  That will help us to
tailor the example.

Good luck!