Indirect Function Calls

print(message)

Direct call

# Call object through original name

Indirect call!

# Now x references the function too

# Call object through name by adding ()

Because arguments are passed by assigning objects, it's just as easy to pass functions to other functions as arguments. The callee may then call the passed-in function just by adding arguments in parentheses: >>> def indirect(func, arg):

... func(arg) # Call the passed-in object by adding ()

>>> indirect(echo, 'Argument call!') # Pass the function to another function Argument call!

You can even stuff function objects into data structures, as though they were integers or strings. The following, for example, embeds the function twice in a list of tuples, as a sort of actions table. Because Python compound types like these can contain any sort of object, there's no special case here, either:

>>> schedule = [ (echo, 'Spam!'), (echo, 'Ham!') ] >>> for (func, arg) in schedule:

... func(arg) # Call functions embedded in containers

Spam! Ham!

This code simply steps through the schedule list, calling the echo function with one argument each time through (notice the tuple-unpacking assignment in the for loop header, introduced in Chapter 13). As we saw in Chapter 17's examples, functions can also be created and returned for use elsewhere:

>>> def make(label): # Make a function but don't call it

>>> F = make('Spam') # Label in enclosing scope is retained

>>> F('Ham!') # Call the function that make returned

Spam:Ham!

Spam:Eggs!

Python's universal object model and lack of type declarations make for an incredibly flexible programming language.

Was this article helpful?

0 -1
Search Engine Manifesto

Search Engine Manifesto

Rank Your Web Pages HIGH in TOP Search Engine Popular Results For Maximum Exposure. Search Engines and How They Work Search Engines are special sites on the Web that are designed to help people find information stored on other sites.

Get My Free Ebook


Post a comment