12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

can usually simulate it by returning tuples and assigning the results back to the originalargument names in the caller:>>> def multiple(x, y):... x = 2 # Changes local names only... y = [3, 4]... return x, y # Return new values in a tuple...>>> X = 1>>> L = [1, 2]>>> X, L = multiple(X, L) # Assign results to caller's names>>> X, L(2, [3, 4])It looks like the code is returning two values here, but it’s really just one—a two-itemtuple with the optional surrounding parentheses omitted. After the call returns, wecan use tuple assignment to unpack the parts of the returned tuple. (If you’ve forgottenwhy this works, flip back to “Tuples” in Chapter 4, and “Assignment Statements”in Chapter 11.) The net effect of this coding pattern is to simulate the output parametersof other languages by explicit assignments. X and L change after the call, but onlybecause the code said so.Special Argument-Matching ModesAs we’ve just seen, arguments are always passed by assignment in <strong>Python</strong>; names inthe def header are assigned to passed-in objects. On top of this model, though, <strong>Python</strong>provides additional tools that alter the way the argument objects in a call are matchedwith argument names in the header prior to assignment. These tools are all optional,but they allow you to write functions that support more flexible calling patterns.By default, arguments are matched by position, from left to right, and you must passexactly as many arguments as there are argument names in the function header. Youcan also specify matching by name, default values, and collectors for extra arguments.Some of this section gets complicated, and before we go into the syntactic details, I’dlike to stress that these special modes are optional, and only have to do with matchingobjects to names; the underlying passing mechanism after the matching takesplace is still assignment. In fact, some of these tools are intended more for peoplewriting libraries than for application developers. But because you may stumbleacross these modes even if you don’t code them yourself, here’s a synopsis of theavailable matching modes:Positionals: matched from left to rightThe normal case, which we’ve been using so far, is to match arguments by position.Keywords: matched by argument nameCallers can specify which argument in the function is to receive a value by usingthe argument’s name in the call, with the name=value syntax.330 | Chapter 16: Scopes and Arguments

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

Saved successfully!

Ooh no, something went wrong!