Understanding Python's Special Methods __len__ and __getitem__ with Example Code
This article explains Python’s double‑underscore special methods such as __len__ and __getitem__, demonstrates their implementation in a FrenchDeck class with example code, shows how they enable built‑in functions like len() and indexing, and further illustrates additional dunder methods using a Vector class.
Python uses special methods whose names start and end with double underscores to implement fundamental object behavior. Two common examples are __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._cards) def __getitem__(self, position): return self._cards[position]
This code defines a FrenchDeck class that implements __len__ and __getitem__ . Implementing __len__ allows the built‑in len() function to return the number of cards, while __getitem__ enables indexing and slicing syntax (e.g., deck[0] or deck[2:5] ).
Example usage:
deck = FrenchDeck() len(deck) # → 52 deck[0] # → Card(rank='2', suit='spades')
The __getitem__ method forwards the [] operation to the internal list self._cards , so the FrenchDeck object automatically supports slicing.
from math import hypot
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
def __abs__(self):
return hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)The Vector class demonstrates additional special methods: __repr__ provides an unambiguous string representation (used by the interpreter), differing from __str__ which is used by print() ; __abs__ defines the magnitude; __bool__ determines truthiness based on the magnitude; __add__ and __mul__ implement addition and scalar multiplication, respectively.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.