I have a Java background and am studying Python's data model. Specifically, I am curious about how and when special methods (e.g. __add__) get called.
It seems like the Python interpreter may execute these special methods when it encounters certain built-in functions. To take an example from the book "Fluent Python", if you have a class like the following FrenchDeck...
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]
then __getitem__ will get called when the Python interpreter encounters things like for card in FrenchDeck() or FrenchDeck()[11].
To me, this seems expressive but also extremely vague. How do I determine what built-in functions will call my special methods? There seems to be some implicit mention of mappings between built-ins and special methods in statements of the Python Data Model section like
It is recommended that both mappings and sequences implement the
__contains__()method to allow efficient use of theinoperator.
But I can't find a clear reference doc with statements like "for user-defined classes, in will use __contains__ if it exists, otherwise it will use __getitem__".