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.

CHAPTER 6 ■ ABSTRACTION 137<br />

As you can see, the left argument is always the largest number found so far, while the right<br />

argument is the next number in the sequence.<br />

■Note You have seen that reduce can be replaced by a for loop, but it cannot be reduced (pun intended)<br />

to a list comprehension because it doesn’t return a list.<br />

apply<br />

Before leaving the subject of functional programming, I’ll touch upon the built-in function<br />

apply. It takes a function as an argument and calls it. You may also optionally supply a tuple of<br />

positional parameters and a dictionary of keyword arguments. You use this if you have a tuple<br />

(or dictionary) of arguments and want to apply a function to it:<br />

>>> def rectangleArea(width, height):<br />

return width * height<br />

>>> rectangle = 20, 30<br />

>>> apply(rectangleArea, rectangle)<br />

600<br />

However, this function is a bit outdated now that you can simply use the nifty little stars to<br />

unpack the arguments (as discussed earlier in this chapter, in the section “Collecting<br />

Parameters”):<br />

>>> rectangleArea(*rectangle)<br />

600<br />

Even though you’ll probably rarely use apply, it has been used extensively in older programs,<br />

and you never know when you’ll have to read someone else’s code.<br />

A Quick Summary<br />

In this chapter, you’ve learned several things about abstraction in general, and functions in<br />

particular:<br />

Abstraction. Abstraction is the art of hiding unnecessary details. You can make your<br />

program more abstract by defining functions that handle the details.<br />

Function definition. Functions are defined with the def statement. They are blocks of<br />

statements that receive values (parameters) from the “outside world” and may return one<br />

or more values as the result of their computation.<br />

Parameters. Functions receive what they need to know in the form of parameters—variables<br />

that are set when the function is called. There are two types of parameters in Python,<br />

positional parameters and keyword parameters. Parameters can be made optional by<br />

giving them default values.

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

Saved successfully!

Ooh no, something went wrong!