import collections
from random import choice
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]
deck = FrenchDeck()
choice(deck)
The error I am getting is:
Traceback (most recent call last):
File "cards.py", line 24, in <module>
choice(deck)
File "C:\Python36\lib\random.py", line 258, in choice
return seq[i]
TypeError: 'FrenchDeck' object does not support indexing
This is from Fluent Python, and I have typed it in as it is in the book. I am wondering if this is an issue that relates to newer Python distributions.
Aucun commentaire:
Enregistrer un commentaire