Книга: Fedora™ Unleashed, 2008 edition

Functions

Functions

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 reads 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 correct one at runtime. Second, you can assign the function to another name just by using =.

A function definition starts with def, followed by the function name, 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 correct 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, as 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. You can 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 you. However, it is this hands-off, "let the objects sort themselves out" attitude that makes functions so flexible. The concat() function could conceivably concatenate strings, lists, or zonks — a data type someone created herself that allows addition. The point is that you do not limit what your function can do — clichй as it might sound, the only limit is your imagination!

Оглавление книги


Генерация: 0.039. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз