12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

172 Chapter 18. Inheritanceif self.suit < other.suit: return -1# suits are the same... check ranksif self.rank > other.rank: return 1if self.rank < other.rank: return -1# ranks are the same... it's a tiereturn 0You can writethismore concisely using tuplecomparison:# inside class Card:def __cmp__(self, other):t1 = self.suit, self.rankt2 = other.suit, other.rankreturn cmp(t1, t2)The built-in function cmp has the same interface as the method __cmp__: it takes two values andreturnsapositivenumberifthefirstislarger,anegativenumberifthesecondislarger,and0iftheyareequal.Exercise 18.1 Write a __cmp__ method for Time objects. Hint: you can use tuple comparison, butyou alsomight consider usinginteger subtraction.18.4 DecksNow that we have Cards, the next step is to define Decks. Since a deck is made up of cards, it isnatural foreach Deck tocontain alistofcards as anattribute.The following is a class definition for Deck. The init method creates the attribute cards and generatesthestandard setof fifty-twocards:class Deck(object):def __init__(self):self.cards = []for suit in range(4):for rank in range(1, 14):card = Card(suit, rank)self.cards.append(card)Theeasiestwaytopopulatethedeckiswithanestedloop. Theouterloopenumeratesthesuitsfrom0to3. Theinnerloopenumeratestheranksfrom1to13. EachiterationcreatesanewCardwiththecurrent suitand rank, and appends ittoself.cards.18.5 Printingthe deckHere isa__str__method forDeck:

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

Saved successfully!

Ooh no, something went wrong!