python從零開始--36 python內建類屬性 __len__ __getitem__ 實現 (補充26節)
阿新 • • 發佈:2018-12-12
在網上看到一個關於實現 __len__ __getitem__的程式碼,剛好作為26節內建類屬性的補充。
程式碼說明:
1. 定義一稿Card具名元組,用來存放撲克點數和花色的組合,FrenchDeck初始化後,剛好是52組資料
2. __len__實現了len(obj)的用法,所以下面可以直接使用len(deck)
3.__getitem__其實實現的是通過索引返回資料的功能,就是列表、元組常用的功能,一旦類實現了這個方法,就可以在這個類的物件上使用 obj[xxx]的寫法,很方便的讀取資料。
import collections Card = collections.namedtuple('Card',['rank','suit']) #具名元組 class FrenchDeck: ranks = [str(n) for n in range(2,11)] + list('JQKA') #牌數 suits = 'spades hearts clubs diamonds'.split() # 牌色 def __init__(self): # 初始化 self._cards = [Card(rank, suit) for rank in self.ranks for suit in self.suits] def __len__(self): # 用len取長度的特殊方法 return len(self._cards) def __getitem__(self, position): # 用索引取值的特殊方法 return self._cards[position] def printAllitem(self): for item in self._cards: print(item) if __name__ == "__main__": deck = FrenchDeck() print("There are total {} cards.".format(len(deck))) print("The third card is: {}".format(deck[2])) print("\nPrint all cards as below:") deck.printAllitem()