1.1 一摞python风格的纸牌
import collections
Card=collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks=[str(n) for n in range(2,11)]+list('JQKA')
# print(ranks)
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]
魔法方法可直接调用类里面的函数方法,实例如下:
deck=FrenchDeck()
print(len(deck))
print(deck[0])
print(deck[-1])
非魔法方法需调用类里面的函数方法,实例如下:
deck=FrenchDeck()
k=deck.len()
print(k)
from random import choice
print(choice(deck))
print(choice(deck))
print(choice(deck))
print(deck[:3])