04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

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

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

124 CHAPTER 6 ■ ABSTRACTION<br />

Also, let’s say you have a tuple with two numbers that you want to add:<br />

params = (1, 2)<br />

This is more or less the opposite of what we did previously. Instead of gathering the<br />

parameters, we want to distribute them. This is simply done by using the asterisk operator in<br />

the “other end,” that is, when calling the function rather than when defining it:<br />

>>> add(*params)<br />

3<br />

This works with parts of a parameter list, too, as long as the expanded part is last. You can<br />

use the same technique with dictionaries, using the double asterisk operator. Assuming that<br />

you have defined hello_3 as before, you can do the following:<br />

>>> params = {'name': 'Sir Robin', 'greeting': 'Well met'}<br />

>>> hello_3(**params)<br />

Well met, Sir Robin!<br />

Using the asterisk (or double asterisk) both when you define and call the function will<br />

simply pass the tuple or dictionary right through, so you might as well not have bothered:<br />

>>> def with_stars(**kwds):<br />

print kwds['name'], 'is', kwds['age'], 'years old'<br />

>>> def without_stars(kwds):<br />

print kwds['name'], 'is', kwds['age'], 'years old'<br />

>>> args = {'name': 'Mr. Gumby', 'age': 42}<br />

>>> with_stars(**args)<br />

Mr. Gumby is 42 years old<br />

>>> without_stars(args)<br />

Mr. Gumby is 42 years old<br />

As you can see, in with_stars, I use stars both when defining and calling the function. In<br />

without_stars, I don’t use the stars in either place but achieve exactly the same effect. So the<br />

stars are only really useful if you use them either when defining a function (to allow a varying<br />

number of arguments) or when calling a function (to “splice in” a dictionary or a sequence).<br />

Example<br />

With so many ways of supplying and receiving parameters, it’s easy to get confused. So let me tie it all together with<br />

an example. First, let me define some functions:<br />

def story(**kwds):<br />

return 'Once upon a time, there was a ' \<br />

'%(job)s called %(name)s.' % kwds<br />

def power(x, y, *others):<br />

if others:

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

Saved successfully!

Ooh no, something went wrong!