1. A Pythonic Card Deck
It demonstrates the power of implementing just two special methods, __getitem__ and __len__.
A deck as a sequence of playing cards.
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]

The use of collections.namedtuple to construct a simple class to represent individual cards.We use namedtuple to build classes of objects that are just bundles of attributes with no custom methods, like a database record.

2.How Special Methods Are Used




3.Collection API

Each of the top ABCs has a single special method. The Collection ABC (new in Python 3.6) unifies the three essential interfaces that every collection should implement:
• Iterable to support for, unpacking, and other forms of iteration
• Sized to support the len built-in function
• Container to support the in operator
Python does not require concrete classes to actually inherit from any of these ABCs. Any class that implements __len__ satisfies the Sized interface.
Three very important specializations of Collection are:
-
Sequence, formalizing the interface of built-ins like list and str
-
Mapping, implemented by dict, collections.defaultdict, etc.
-
Set, the interface of the set and frozenset built-in types
Only Sequence is Reversible, because sequences support arbitrary ordering of their contents, while mappings and sets do not.
4. Overview of Special Methods




被折叠的 条评论
为什么被折叠?



