-
Notifications
You must be signed in to change notification settings - Fork 0
/
french_deck.py
57 lines (32 loc) · 1021 Bytes
/
french_deck.py
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
49
50
51
# -*- coding: utf-8 -*-
from collections import namedtuple
from random import shuffle
class FrenchDeck:
Card = namedtuple('Card', ['rank', 'suit'])
# print(Card('aa', 13))
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [self.Card(rank, suit) for suit in self.suits for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, pos):
return self._cards[pos]
# def __setitem__(self, pos, val):
# rst = self._cards[pos] = val
#
# return rst
def set_card(deck, pos, card):
deck._cards[pos] = card
if __name__ == '__main__':
deck = FrenchDeck()
print(deck._cards)
# 猴子补丁
FrenchDeck.__setitem__ = set_card
# 打乱原来的列表的顺序
shuffle(deck)
print(deck[:5])
print(deck[0])
print(deck[0].rank, deck[0].suit)
print(dir(deck[0]))
print(len(deck))