Now that we have Card objects, the next step is to define a class to represent decks. Since a deck is made up cards, a natural choice is for each Deck object to contain a list of cards as an attribute. The following is a class definition for Deck. The init method creates the attribute cards and generates the standard set of fifty-two cards:
class Deck: """represents a standard Deck instance attributes: cards """ def __init__(self): self.cards = [] for suit in range(4): for rank in range(1,14) card = Card(suit,rank) self.cards.append(card)
The easiest way to populate the deck is with a nested loop. The outer loop enumerates the suits from 0 to 3. The inner loop enumerates the ranks from 1 to 13. Each iteration of the inner loop creates a new Card with current suit and rank, and appends it to self.cards.
Printing the deck
Here is a str method for Deck:
def __str__(self): temp = [] for card in self.cards: temp.append(str(card)) return ‘\n‘.join(temp)
The method demonstrates an efficient way to accumulate a large string, by building a list of strings and then using join. The built-in function str invokes the __str__ method on each card and returns the string representation. Since we invoke join on a newline character, the cards are separated by newlines.
........
from Thinking in Python