11.4 Transfer function:

11.4 Transfer function:

The concept of function pointers is an advanced topic when learning a language like C, but functions are just like any other object.

Not so with Python.

Functions can be referenced (accessed or aliased to other variables), passed as arguments to functions, and as lists and

fields, etc. elements of container objects.

Because all objects are passed by reference, functions are no exception. When assigning a value to a variable, the actual

A reference to the same object is assigned to this variable.

def foo():
    print 'in foo()'
bar=foo
bar()

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/eee/a3.py
in foo()


def foo():
    print 'in foo()'

def bar(xx):
    foo()
print bar(foo)

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/eee/a3.py
in foo()
None

A more practical example of passing functions as parameters and calling those functions within the function body. This script uses the incoming

The conversion function simply converts a sequence of numbers to the same type.

def convert(func,seq):
     print func(seq)
     print type(func(seq))
a=123
print type(a)
print convert(str,a)



C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/eee/a4.py
<type 'int'>
123
<type 'str'>
None

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324802115&siteId=291194637