一丶序幕
1.特殊方法名的作用
特殊方法名能让你自己的对象实现和支持以下的语言构架,并与之交互:
- 迭代
- 集合类
- 属性访问
- 运算符重载
- 函数和方法的调用
- 对象的创建和销毁
- 字符串表示形式和格式化
- 管理上下文(即 with 块)
import collections#创建一个类表示纸牌#nametuple方法用于构建只有少数属性但没有方法的对象:#>>> beer_card = Card("7","diamonds")#>>> beer_card#Card(rank='7', suit='diamonds')#Card = collections.namedtuple("Card",["rank","suit"])#花色英文展示#hearts红心#diamonds红方#spades黑桃#clubs草花#查看一叠牌有多少张#主要还是关注FrenchDeck类,len()函数可以查看一叠牌有多少张#>>> deck = FrenchDeck()#>>> len(deck)#52#抽取固定顺序的牌#从一叠牌中抽取第一张和最后一张牌非常容易,这都是由__getitem__方法提供的#>>> deck[0]#Card(rank='2', suit='spades')#>>> deck[-1]#Card(rank='A', suit='hearts')#抽取随机的牌#from random import choice#choice(deck)#Card(rank='6', suit='spades')#>>> choice(deck)#Card(rank='6', suit='hearts')#>>> choice(deck)#Card(rank='8', suit='diamonds')#代码演示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] suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0) def spades_high(card): rank_value = FrenchDeck.ranks.index(card.rank) return rank_value * len(suit_values) + suit_values[card.suit]