Of course, defining a function is only half of the puzzle - for it to be of any use at all, you need to invoke it. In Python, as in Perl, PHP and a million other languages, this is accomplished by "calling" the function by its name, as I've done in the last line of the example above. Calling a user-defined function is identical to calling a built-in Python function like print() or type(). It should be noted that Python will barf if you attempt to call a function before it has been defined - look what happens when I try the following example: Here's the output: Another important thing to remember about functions is that they're, at heart, objects...just like everything else in Python. Consequently, they can be assigned to other objects, passed as values or data structures, and otherwise treated as though they were any other Python object. The following example demonstrates this object-oriented behaviour, by assigning one function to another, and then using the new assignment to invoke the function. And the output is:
blog comments powered by Disqus |