The Python dunder methods

Much of Python's special syntax is there to access special methods of the object in question. For example a[x] is special syntax for a.__getitem__(x), a call to the __getitem__ special method of the object a.

To see how the __getitem__ and __len__ special methods work, let's take as an example a deck of playing cards, a so-called French deck.

import collections

Card = collections.namedtuple("Card", ["rank", "suit"])


class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list("JQKA")
    suits = list("♠♦♣♥")

    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]

Now we can make a card

Card(7, '♥')
Card(rank=7, suit='♥')

And indeed a deck

deck = FrenchDeck()
len(deck)
52

Here we use the len() syntax which calls the __len__ method of the FrenchDeck object.

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-09-04 Thu 08:56