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.6. Add, remove, shuffle and sort 173#inside class Deck:def __str__(self):res = []for card in self.cards:res.append(str(card))return '\n'.join(res)Thismethoddemonstratesanefficientwaytoaccumulatealargestring: buildingalistofstringsandthen using join. The built-in function str invokes the __str__ method on each card and returnsthestringrepresentation.Since we invoke join on a newline character, the cards are separated by newlines. Here’s what theresultlooks like:>>> deck = Deck()>>> print deckAce of Clubs2 of Clubs3 of Clubs...10 of SpadesJack of SpadesQueen of SpadesKing of SpadesEven though theresult appears on 52lines, itisone long stringthat contains newlines.18.6 Add,remove,shuffle and sortTo deal cards, we would like a method that removes a card from the deck and returns it. The listmethodpopprovides a convenient way todothat:#inside class Deck:def pop_card(self):return self.cards.pop()Since pop removes the last card in the list, we are dealing from the bottom of the deck. In real lifebottom dealing isfrowned upon 1 ,but inthis context it’sok.To add acard, wecan usethelistmethodappend:#inside class Deck:def add_card(self, card):self.cards.append(card)A method like this that uses another function without doing much real work is sometimes called aveneer. The metaphor comes from woodworking, where it is common to glue a thin layer of goodquality wood tothe surfaceof acheaper piece ofwood.1 Seewikipedia.org/wiki/Bottom_dealing

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

Saved successfully!

Ooh no, something went wrong!