04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

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

CHAPTER 7 ■ MORE ABSTRACTION 151<br />

>>> f = FoodExpert()<br />

>>> f.init()<br />

>>> map(f.addGoodFood, ['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise'])<br />

[None, None, None, None, None]<br />

The first two lines instantiate FoodExpert and initialize the instance, which is assigned to f.<br />

The map call simply uses the method addGoodFood with its self parameter bound to f. Because<br />

this method doesn’t return anything, the result is a list filled with None. However, a side effect is<br />

that f has been updated:<br />

>>> f.goodFood<br />

['SPAM', 'Eggs', 'Bacon', 'Rat', 'Spring Surprise']<br />

Let’s use this expert to give us a list of recommendations:<br />

>>> menu = ['Filet Mignon', 'Pasta', 'Pizza', 'Eggs', 'Bacon', 'Tomato', 'SPAM']<br />

>>> rec = filter(f.likes, menu)<br />

>>> rec<br />

['Eggs', 'Bacon', 'SPAM']<br />

What I did here was simply apply f.likes as a filter to a menu; the dishes the expert didn’t<br />

like were simply discarded. But what if you want to find out which of these dishes the expert<br />

would prefer? I once again turn to the trusty (if rarely used) reduce:<br />

>>> reduce(f.prefers, rec)<br />

'SPAM'<br />

This basically works just like the example using reduce with max in Chapter 6 (in the section<br />

“reduce”).<br />

If I had used a different expert, initialized with different preferences, of course, I’d get<br />

completely different results, even though the method definitions would be exactly the same. This<br />

is the primary difference between standard functional programming and this quasi-functional<br />

programming using bound methods; the methods have access to a state that can be used to<br />

“customize” them.<br />

■Note You can pass state along with a function like this by using nested scopes as well, as discussed in<br />

the previous chapter.<br />

The Class Namespace<br />

The following two statements are (more or less) equivalent:<br />

def foo(x): return x*x<br />

foo = lambda x: x*x

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

Saved successfully!

Ooh no, something went wrong!