import collections
Card = collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]A pythonic card deck
We can use a namedtuple to build classes of objects that are just bundles of attributes with no custom methods, like a database record. In the example, we use it to provide a nice representation for the cards in the deck, as shown in the console session below:
The point of this example is actually the FrenchDeck class. FrenchDeck is a sequence. We can access a card by its position and we can iterate through the FrenchDeck.
Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
Card(rank='4', suit='spades')
Card(rank='5', suit='spades')
Card(rank='6', suit='spades')
We can also pick a random card using the random module from the standard library.
Its easier to benefit from the rich Python standard library and avoid reinventing the wheekl like the random.choice() function.
How about sorting cards? A common system of ranking cards is by rank(with aces being highest) and then by suit in the order of spades