16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

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 />

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

self parameter <strong>to</strong> 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 <strong>to</strong>ols 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-explana<strong>to</strong>ry.<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 <strong>to</strong><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 <strong>to</strong> 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 <strong>to</strong> 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!