I have Java training and I study the Python data model. More specifically, I'm curious to know how and when special methods (e.g.
__add__) call themselves.
It seems that the Python interpreter can execute these special methods when it encounters some built-in functions. To take an example from the book "Fluent Python", if you have a class like the following
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)
__getitem__ will be called when the Python interpreter encounters things like
for card in FrenchDeck() or
It seems expressive but also extremely vague. How can I determine which built-in functions call my special methods? There seems to be an implicit mention of mappings between built-in and special methods in the instructions in the Python Data Model section like
It is recommended that mappings and sequences implement the
__contains__()to allow efficient use of the
But I can't find a clear reference document with instructions like "for user-defined classes,
__contains__ if it exists, otherwise it will use