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]
# 重新len方法
def __len__(self):
return len(self._cards)
# 重写getitem方法
def __getitem__(self, item):
return self._cards[item]
if __name__ == '__main__':
beer_card = Card('7', 'diamonds')
print(beer_card.rank)
deck = FrenchDeck()
print(len(deck)) # 一叠牌有多少张
print(deck[0]) # 抽取第一张纸牌
print(choice(deck)) # 随机抽取一张纸牌
print(deck[:3]) # 查看一摞牌最上面3张
print(Card('Q', 'hearts') in deck) # 是可迭代的
【Python进阶学习】1.__len__和__getitem__实现
最新推荐文章于 2024-11-10 13:43:20 发布