15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

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

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

11.2. Calling Functions<br />

11.2.1. Function Operator<br />

Functions are called using the same pair of parentheses that you are used to. In fact, some consider<br />

( () ) to be a two-character operator, the function operator. As you are probably aware, any input<br />

parameters or arguments must be placed between these calling parentheses. Parentheses are also used<br />

as part of function declarations to define those arguments. Although we have yet to formally study<br />

classes and object-oriented programming, you will discover that the function operator is also used in<br />

<strong>Python</strong> for class instantiation.<br />

11.2.2. Keyword Arguments<br />

The concept of keyword arguments applies only to function invocation. The idea here is for the caller to<br />

identify the arguments by parameter name in a function call. This specification allows for arguments to<br />

be missing or out-of-order because the interpreter is able to use the provided keywords to match values<br />

to parameters.<br />

For a simple example, imagine a function foo(), which has the following pseudocode definition:<br />

def foo(x):<br />

foo_suite # presumably does some processing with 'x'<br />

Standard calls to foo(): foo(42) foo('bar') foo(y)<br />

Keyword calls to foo(): foo(x=42) foo(x='bar') foo(x=y)<br />

For a more realistic example, let us assume you have a function called net_conn() and you know that it<br />

takes two parameters, say, host and port:<br />

def net_conn(host, port):<br />

net_conn_suite<br />

Naturally, we can call the function, giving the proper arguments in the correct positional order in which<br />

they were declared:<br />

net_conn('kappa', 8080)<br />

The host parameter gets the string 'kappa' and port gets integer 8080. Keyword arguments allow out-oforder<br />

parameters, but you must provide the name of the parameter as a "keyword" to have your<br />

arguments match up to their corresponding argument names, as in the following:<br />

net_conn(port=8080, host='chino')

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

Saved successfully!

Ooh no, something went wrong!