import collections
from random import choice
# namedtuple 是一个可命名的元祖,它可以让你使用属性式的标签来访问元祖中的元素,而不是通过索引
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDesk:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suite = '黑桃 方块 梅花 红星'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suite
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
# 手工设置一张牌
beer_card = Card('7', '方块')
print("手工设置一张牌:")
print(beer_card.rank, beer_card.suit)
deck = FrenchDesk()
print(f"总共有 {len(deck)} 张牌。")
print(deck[0])
print(deck[-1])
# 随机选一张牌
# 函数random.choice 可以从序列中随机获取一项的函数
print("随机获取的牌:")
print(choice(deck))
print(choice(deck))
print(choice(deck))
Fluent Python 1-1