1.利用简单的例子来展示实现 __getitem__ __len__ 这2个特殊方法
定义一个字牌类
#encoding:utf-8 import collections 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] def __len__(self): return len(self._cards) def __getitem__(self, position): return self._cards[position]
利用 namedtuple方法 得到一个字牌的对象
beer_card = Card('7', 'diamonds') print(beer_card) #Card(rank='7', suit='diamonds') print(beer_card.rank) #7 print(beer_card.suit) #diamonds #可以用 len() 函数来查看一叠牌有多少张: deck = FrenchDeck() print(len(deck)) #52