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.

150 CHAPTER 7 ■ MORE ABSTRACTION<br />

■Note In Chapter 9, you see how classes can call methods in their superclasses (more specifically, the<br />

constructors of their superclasses). Those methods are called directly on the class; they haven’t bound their<br />

self parameter to anything and are therefore called unbound methods.<br />

Throwing Methods Around<br />

In the previous section, I showed how you could use a bound method just like a function<br />

without losing the self parameter. That means that you can use methods in many of the fancy<br />

ways that I’ve used functions previously, with handy tools such as map, filter, and reduce (see<br />

the section “Throwing Functions Around” in Chapter 6). In this section, I provide some examples<br />

of these capabilities. They should all be fairly self-explanatory.<br />

Let’s start by creating a class:<br />

class FoodExpert:<br />

def init(self):<br />

self.goodFood = []<br />

def addGoodFood(self, food):<br />

self.goodFood.append(food)<br />

def likes(self, x):<br />

return x in self.goodFood<br />

def prefers(self, x, y):<br />

x_rating = self.goodFood.index(x)<br />

y_rating = self.goodFood.index(y)<br />

if x_rating > y_rating:<br />

return y<br />

else:<br />

return x<br />

This class has more code than earlier examples, but it is still pretty simple. It is meant to<br />

represent some sort of food expert (as the name implies) who likes only some types of food, and<br />

likes some more than others.<br />

The init method simply initializes the objects by giving them an attribute called goodFood<br />

containing an empty list. The addGoodFood method adds a type of food to the list, where the first<br />

food type added is the expert’s favorite, the next one is the second choice, and so on. The likes<br />

method simply checks whether the expert likes a certain type of food (whether it has been<br />

added to goodFood), and finally the prefers method is given two food types (both of which must<br />

be liked) and returns the preferred one (based on their position in goodFood).<br />

Now, let’s play. In the following example, a FoodExpert is created and its taste buds<br />

initialized:

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

Saved successfully!

Ooh no, something went wrong!