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.

170 Chapter 18. InheritanceJack ↦→ 11Queen ↦→ 12King ↦→ 13I am using the ↦→ symbol to make it clear that these mappings are not part of the <strong>Python</strong> program.They arepart of the program design, but they don’t appear explicitly inthe code.The class definition forCardlooks likethis:class Card(object):"""represents a standard playing card."""def __init__(self, suit=0, rank=2):self.suit = suitself.rank = rankAs usual, the init method takes an optional parameter for each attribute. The default card is the 2 ofClubs.To create aCard, you callCardwiththesuitand rankof the card you want.queen_of_diamonds = Card(1, 12)18.2 ClassattributesIn order to print Card objects in a way that people can easily read, we need a mapping from theinteger codes to the corresponding ranks and suits. A natural way to do that is with lists of strings.We assigntheseliststoclass attributes:# inside class Card:suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7','8', '9', '10', 'Jack', 'Queen', 'King']def __str__(self):return '%s of %s' % (Card.rank_names[self.rank],Card.suit_names[self.suit])Variables like suit_names and rank_names, which are defined inside a class but outside of anymethod, are called classattributes because they areassociated withtheclass objectCard.This term distinguishes them from variables like suit and rank, which are called instance attributesbecause they areassociated withaparticular instance.Both kinds of attribute are accessed using dot notation. For example, in __str__, self is a Cardobject, and self.rank is its rank. Similarly, Card is a class object, and Card.rank_names is a listof stringsassociated withtheclass.Everycardhasitsownsuitandrank,butthereisonlyonecopyofsuit_namesandrank_names.Puttingitalltogether,theexpressionCard.rank_names[self.rank]means“usetheattributerankfrom the object self as an index into the list rank_names from the class Card, and select theappropriate string.”

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

Saved successfully!

Ooh no, something went wrong!