11.4. 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 such as 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., they 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 callable: >>> 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.3. Example 11.3. Passing and Calling (Built-in) Functions (numConv.py)
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] |