See All Titles |
![]() ![]() Passing FunctionsThe concept of function pointers is an advanced topic when learning a language such as C, but not Python where functions are like any other object. They can be referenced (accessed or aliased to other variables), passed as arguments to functions, be elements of container objects like lists and dictionaries, etc. The one unique characteristic of functions which may set them apart from other objects is that they are callable, i.e., can be invoked via the function operator. (There are other callables in Python. For more information see Chapter 14) In the description above, we noted that functions can be aliases to other variables. Because all objects are passed by reference, functions are no different. When assigning to another variable, you are assigning the reference to the same object; and if that object is a function, then all aliases to that same object are invokable: >>> def foo(): … print 'in foo()' … >>> bar = foo >>> bar() in foo() When we assigned foo to bar, we are assigning the same function object to bar, thus we can invoke bar() in the same way we call foo(). Be sure you understand the difference between "foo" (reference of the function object) and "foo()" (invocation of the function object) Taking our reference example a bit further, we can even pass functions in as arguments to other functions for invocation: >>> def bar(argfunc): … argfunc() … >>> bar(foo) in foo() Note that it is the function object foo that is being passed to bar().bar() is the function that actually calls foo() (which has been aliased to the local variable argfunc in the same way that we assigned foo to bar in the previous example). Now let us examine a more realistic example, numconv.py, whose code is given in Example 11.1. Example 11.1. Passing and Calling (Built-in) Functions (numconv.py)A more realistic example of passing functions as arguments and invoking them from within the function. This script simply converts a sequence of numbers to the same type using the conversion function that is passed in. In particular, the test() function passes in a built-in function int(), long(), or float() to perform the conversion. <$nopage> 001 1 #!/usr/bin/env python 002 2 003 3 def convert(func, seq): 004 4 'conv. sequence of numbers to same type' 005 5 newSeq = [] 006 6 for eachNum in seq: 007 7 newSeq.append(func(eachNum)) 008 8 return newSeq 009 9 010 10 def test(): 011 11 'test function for numconv.py' 012 12 myseq = (123, 45.67, -6.2e8, 999999999L) 013 13 print convert(int, myseq) 014 14 print convert(long, myseq) 015 15 print convert(float, myseq) 016 16 017 17 if __name__ == '__main__': 018 18 test() 019 <$nopage> If we were to run this program, we would get the following output: % numconv.py [123, 45, -620000000, 999999999] [123L, 45L, -620000000L, 999999999L] [123.0, 45.67, -620000000.0, 999999999.0]
|
© 2002, O'Reilly & Associates, Inc. |