import collections
from random import choice
# AAAAAAAA(rank='spades', suit='2') 出来的名字是括号里的‘Card’
Card = collections.namedtuple('Card', ['rank', 'suit'])
t_card = Card('7', 'hearts')
print t_card
ranks = [str(n) for n in range(2,11)] + list('JQKA')
print ranks
suits = 'spades diamonds clubs hearts'.split()
print suits
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(suit, rank) for suit in suits for rank in ranks]
# 当类作为一系列值的容器时,一般是需要__len__的
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
card = FrenchDeck()
# 调用的实际是__len__ ,如果你在__len__中return N ,返回的也是N
print len(card)
# 实际调用的是 __getitem__。只要是对实例[]的操作__getitem__把操作交给self._cards
print card[0]
# choice的调用类中必须有__len__和__getitem__
print choice(card)
# <type 'instance'> card实际只是一个实例,对他的操作需要各种内置函数。
print type(card)
# 对card的迭代操作,card[0],card[1],card[2],card[3].....
for a in card:
print a
FluentPython读书笔记1--1.1
最新推荐文章于 2022-05-27 15:31:56 发布