-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdunder_getitem.py
More file actions
48 lines (38 loc) · 1.22 KB
/
dunder_getitem.py
File metadata and controls
48 lines (38 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import collections
"""
>>> Card('7', 'diamonds')
Card(rank='7', suit='diamonds')
"""
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
"""
By implenting __len__ and __getitem__, you leverage the Python Data Model
"""
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):
"""
>>> deck = FrenchDeck()
>>> len(deck) # what __len__ provides
52
"""
return len(self._cards)
def __getitem__(self, position):
"""
>>> deck = FrenchDeck()
>>> deck[0] # what __getitem__ provides
Card(rank='2', suit='spades')
>>> deck[:2] # with slicing supported
[Card(rank='2', suit='spades'), Card(rank='3', suit='spades')]
>>> for card in reversed(deck): # with iteration supported
... print(card);
... break
Card(rank='A', suit='hearts')
"""
return self._cards[position]
if __name__ == "__main__":
import doctest
doctest.testmod()