10.6.3 Class DeckOfCards

  • Class attribute NUMBER_OF_CARDS represents the number of Cards in a deck
  • Data attribute _current_card keeps track of which Card will be dealt next (051)
  • Data attribute _deck is a list of 52 Card objects

Method __init__

  • Initializes a _deck of Cards
  • for statement fills the list _deck by appending new Card objects, each initialized with two strings—one from the list Card.FACES and one from Card.SUITS
# deck.py
"""Deck class represents a deck of Cards."""
import random 
from card import Card

class DeckOfCards:
    NUMBER_OF_CARDS = 52  # constant number of Cards

    def __init__(self):
        """Initialize the deck."""
        self._current_card = 0
        self._deck = []

        for count in range(DeckOfCards.NUMBER_OF_CARDS):  
            self._deck.append(Card(Card.FACES[count % 13], 
                Card.SUITS[count // 13]))

Method shuffle

  • Resets _current_card to 0, then shuffles the Cards in _deck using the random module’s shuffle function
def shuffle(self):
        """Shuffle deck."""
        self._current_card = 0
        random.shuffle(self._deck)

Method deal_card

  • Deals one Card from _deck
  • Returns None when there are no more Cards to deal
def deal_card(self):
        """Return one Card."""
        try:
            card = self._deck[self._current_card]
            self._current_card += 1
            return card
        except:
            return None

Method __str__

  • Returns a string representation of the deck in four columns with each Card left aligned in a field of 19 characters
def __str__(self):
        """Return a string representation of the current _deck."""
        s = ''

        for index, card in enumerate(self._deck):
            s += f'{self._deck[index]:<19}'
            if (index + 1) % 4 == 0:
                s += '\n'

        return s

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.