12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

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.

18.3. Comparing cards 171Thefirstelementofrank_namesisNonebecausethereisnocardwithrankzero. ByincludingNoneas a place-keeper, we get a mapping with the nice property that the index 2 maps to the string'2',and soon. To avoid thistweak, we could have used adictionary instead of alist.Withthe methods wehave sofar,wecan create and print cards:>>> card1 = Card(2, 11)>>> print card1Jack of HeartsHere isadiagram that shows theCardclass object and one Card instance:Cardtypesuit_namesrank_nameslistlistcard1Cardsuitrank111Card is a class object, so it has type type. card1 has type Card. (To save space, I didn’t draw thecontents ofsuit_namesandrank_names).18.3 ComparingcardsFor built-in types, there are relational operators (, ==, etc.) that compare values and determinewhen one is greater than, less than, or equal to another. For user-defined types, we can override thebehavior of thebuilt-inoperators by providing amethod named__cmp__.__cmp__ takes two parameters, self and other, and returns a positive number if the first object isgreater, anegative number if thesecond object isgreater, and 0ifthey areequal toeach other.The correct ordering for cards is not obvious. For example, which is better, the 3 of Clubs or the 2ofDiamonds? Onehasahigherrank,buttheotherhasahighersuit. Inordertocomparecards,youhave todecide whether rank or suitismoreimportant.The answer might depend on what game you are playing, but to keep things simple, we’ll make thearbitrarychoicethatsuitismoreimportant,soalloftheSpadesoutrankalloftheDiamonds,andsoon.Withthat decided, wecan write__cmp__:# inside class Card:def __cmp__(self, other):# check the suitsif self.suit > other.suit: return 1

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

Saved successfully!

Ooh no, something went wrong!