fluent Python
1.1 Python风格的纸牌
Python collections模块中的内置模块:namedtuple
https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001411031239400f7181f65f33a4623bc42276a605debf6000
import collections
Card = collections.namedtuple('Card',['rank','suit']) # 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 rank in self.ranks
for suit in self.suits]
def __len__(self):
return len(self._cards)
def __getitem__(self,position):
return self._cards[position]
deck = FrenchDeck()
print(len(deck))
print(deck[0])