具名元祖可以方便的声明一个数据类型,像是一个小型的类,来看下面这个栗子
from collections import namedtuple
Card = namedtuple("Card", "rank suit")
class Poker:
ranks = [str(n) for n in range(2, 11)] + list("JQKA")
suits = "spades hearts diamonds clubs".split()
def __init__(self):
self.cards = [Card(c, s) for s in self.suits
for c in self.ranks]
def __len__(self):
return len(self.cards)
def __getitem__(self, item):
return self.cards[item]
p = Poker()
print(p.cards)
print(len(p.cards))