12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

seen some of these uses in earlier examples. Function objects also happen to supporta special operation: they can be called by listing arguments in parentheses after afunction expression. Still, functions belong to the same general category as otherobjects.For instance, there’s really nothing special about the name used in a def statement:it’s just a variable assigned in the current scope, as if it had appeared on the left of an= sign. After a def runs, the function name is simply a reference to an object, and youcan reassign that object to other names, and call it through any reference (not justthe original name):>>> def echo(message): # echo assigned to a function object... print message...>>> x = echo # Now x references it too>>> x('Hello world!') # Call the object by adding ( )Hello world!Because arguments are passed by assigning objects, it’s just as easy to pass functionsto other functions as arguments. The callee may then call the passed-in function justby adding arguments in parentheses:>>> def indirect(func, arg):... func(arg) # Call the object by adding ( )...>>> indirect(echo, 'Hello jello!') # Pass the function to a functionHello jello!You can even stuff function objects into data structures, as though they were integersor strings. Because <strong>Python</strong> compound types 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)...Spam!Ham!This code simply steps through the schedule list, calling the echo function with oneargument each time through (notice the tuple-unpacking assignment in the for loopheader, introduced in Chapter 13). <strong>Python</strong>’s lack of type declarations makes for anincredibly flexible programming language.Function GotchasFunctions have some jagged edges that you might not expect. They’re all obscure,and a few have started to fall away from the language completely in recent releases,but most have been known to trip up new users.Function Gotchas | 371

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!