import collections
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) #index返回参数在对象中第一次出现的位置
return rank_value * len(suit_values) + suit_values[card.suit]
deck = FrenchDeck()
len(deck)
deck.__len__()
FrenchDeck.__len__(deck)
#All these forms are avaible,编译器会将这三种表达方式都解释为同一指令
for card in deck: #由于定义了__getitem__方法,所以FrenchDeck类的所有对象都是可迭代的
pass
for card in sorted(deck):
print(card)
__contains__方法
__contains__方法和 in 息息相关,举例
>>> str1 = "abcdefg"
>>> str2 = "bcd"
>>> val = str1.__contains__(str2)
>>> val
True
?只要一个对象是可迭代的,即使它没有__contains__属性,in可以以循环的方式在该对象中搜寻。
__getitem__方法
如果一个对象拥有了__getitem__属性,那么它可以被搜寻,被迭代。
|