先给个例子:
>>> 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]
魔法方法又称双下划线方法,或者dunder method
通过魔法方法,可以赋予类一些build-in的操作,
比如:
>>> deck = FrenchDeck()
>>> len(deck)
52
而且魔法方法比直接调用普通的方法更快
因为存在getitem方法,还可以:
>>> deck[0]
Card(rank='2', suit='spades')
所以也支持切片迭代等操作:
>>> deck[-3:-1]
[Card(rank='Q', suit='hearts'), Card(rank='K', suit='hearts')]
也支持in 操作符
>>> for card in deck:
print(card)
Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
...