Protocols and duck typing in Python

refer to:

  1. Fluent_Python - P430
  2. wiki

What is the agreement mentioned here?

  1. In object-oriented programming, protocols are informal interfaces that are only defined in documentation, not in code.
  2. In Python, protocols should be treated as formal interfaces.
  3. 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

  1. 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
  2. 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.

  1. 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.
  2. 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324618116&siteId=291194637