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.

DefaultsWe talked a little about defaults earlier, when discussing nested function scopes. Inshort, defaults allow us to make selected function arguments optional; if not passed avalue, the argument is assigned its default before the function runs. For example,here is a function that requires one argument, and defaults two:>>> def f(a, b=2, c=3): print a, b, c...When we call this function, we must provide a value for a, either by position or bykeyword; however, providing values for b and c is optional. If we don’t pass values tob and c, they default to 2 and 3, respectively:>>> f(1)1 2 3>>> f(a=1)1 2 3If we pass two values, only c gets its default, and with three values, no defaults areused:>>> f(1, 4)1 4 3>>> f(1, 4, 5)1 4 5Finally, here is how the keyword and default features interact. Because they subvertthe normal left-to-right positional mapping, keywords allow us to essentially skipover arguments with defaults:>>> f(1, c=6)1 2 6Here, a gets 1 by position, c gets 6 by keyword, and b, in between, defaults to 2.Be careful not to confuse the special name=value syntax in a function header and afunction call; in the call, it means a match-by-name keyword argument, and in theheader, it specifies a default for an optional argument. In both cases, this is not anassignment statement; it is special syntax for these two contexts, which modifies thedefault argument-matching mechanics.Arbitrary Arguments ExamplesThe last two matching extensions, * and **, are designed to support functions thattake any number of arguments. Both can appear in either the function definition, or afunction call, and they have related purposes in the two locations.Special Argument-Matching Modes | 333

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

Saved successfully!

Ooh no, something went wrong!