Functions

 < Day Day Up > 

The way Python handles functions is unique, fun, and quite unlike most other mainstream languages. The two basic tenets of Python functions are that they are defined at runtime and they are typeless.

Other languages such as PHP read and process an entire file before executing it, which means you can call a function before it is defined because the compiler will read the definition of the function before it tries to call it. Python is different: If the function definition has not been reached by the time you try to call it, you get an error. The reason behind this behavior is that Python actually creates an object for your function, and that in turns means two things. First, you can define the same function several times in a script and have the script pick the right one at runtime. Second, you can assign the function to another name just by using =.

Function definition starts with def, then the function name, then parentheses and a list of parameters, and then a colon. The contents of a function need to be indented at least one level beyond the definition. So, using function assignment and dynamic declaration, you can write a script that prints the right greeting in a roundabout manner:

 >>> def hello_english(Name): ...     print "Hello, " + Name + "!" ... >>> def hello_hungarian(Name): ...     print "Szia, " + Name + "!" ... >>> hello = hello_hungarian >>> hello("Paul") Szia, Paul! >>> hello = hello_english >>> hello("Paul") 

Notice that function definitions include no type information. Functions are typeless, like we said. The upside of this is that you can write one function to do several things:

 >>> def concat(First, Second): ...     return First + Second ... >>> concat(["python"], ["perl"]) ['python', 'perl'] >>> concat("Hello, ", "world!") 'Hello, world!' 

That demonstrates how the return statement sends a value back to the caller, but also how a function can do one thing with lists and another thing with strings. The magic here is being accomplished by the objects. We write a function that tells two objects to add themselves together, and the objects intrinsically know how to do that. If they don't if, perhaps, the user passes in a string and an integer Python catches the error for us. However, it is this hands-off, "let the objects sort themselves out" attitude that makes functions so flexible. Our concat() function could conceivably concatenate strings, lists, or zonks a data type someone created herself that allows adding. The point is that we do not limit what our function can do tacky as it might sound, the only limit is your imagination!

     < Day Day Up > 


    Red Hat Fedora 4 Unleashed
    Red Hat Fedora 4 Unleashed
    ISBN: 0672327929
    EAN: 2147483647
    Year: 2006
    Pages: 361

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