refer to:
- Fluent_Python - P430
- wiki
What is the agreement mentioned here?
- In object-oriented programming, protocols are informal interfaces that are only defined in documentation, not in code.
- In Python, protocols should be treated as formal interfaces.
- Various protocols exist in Python for implementing duck typing . (If you need to become the corresponding duck type, then implement the relevant protocol, that is, the relevant __method__)
Duck Typing
- When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck. - James Whitcomb Riley
- Do not pay attention to the type of the object, but focus on the behavior (method) of the object. Its behavior is the behavior of a duck, then it can be considered a duck.
Example 1. Make the FrenchDeck class behave like a Python sequence, and FrenchDeck is a duck type.
- It doesn't matter which class the FrenchDeck class is a subclass of or what type it is. Just provide the methods you want, e.g. behave like a sequence.
- Python's sequence protocol only requires two methods, __len__ and __getitem__.
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._cars)
def __getitem__(self, position):
return self._cards[position]
Here, FrenchDeck implements the __len__ and __getitem__ methods required by the Python sequence protocol, which is duck typing and behaves like a sequence.