前言
本文为《流畅的python》的1.1节的学习笔记。
collections.namedtuple
这个方法,使用场景为只有少数属性但没有方法的对象。
使用方法
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 suit in self.suits
for rank in self.ranks]
由这个类,构建了一副纸牌点数由2到A,纸牌花色由黑桃到红心。
deck = FrenchDeck()
print("******************** print deck ********************")
for card in deck:
print(card)
'''
result
******************** print deck ********************
Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
......
Card(rank='K', suit='hearts')
Card(rank='A', suit='hearts')
'''
获取任意纸牌
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 __getitem__(self, position):
return self._cards[position]
通过添加__getitem__()方法,可获得纸牌的特定的某张牌。
#code
print(deck[0])# get the first one
print(deck[-1])# get the last one
'''
result:
Card(rank='2', suit='spades')
Card(rank='A', suit='hearts')
'''
总结
- 何时使用collections.namedtuple
- getitem()方法的作用