Section 11.4. Passing Functions


11.4. Passing Functions

The 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)

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.

1  #!/usr/bin/env python 2 3  def convert(func, seq): 4      'conv. sequence of numbers to same type' 5      return [func(eachNum) for eachNum in seq] 6 7  myseq = (123, 45.67, -6.2e8, 999999999L) 8  print convert(int, myseq) 9  print convert(long, myseq) 10 print convert(float, myseq)

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]




Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net