Python Reference ยท Classes and Special Methods
__len__() and __getitem__()
Reference for Python __len__, __getitem__, __setitem__, __delitem__ and __contains__: building sequence and mapping classes, slices and the old iteration fallback.
A few special methods let your own classes behave like lists and dictionaries. __len__() powers len(obj), __getitem__() powers obj[key], __setitem__() powers obj[key] = value, __delitem__() powers del obj[key] and __contains__() powers x in obj.
Define these and your objects work with indexing, slicing, for loops, reversed(), in and many built-ins, without inheriting from list.
class Deck: def __init__(self, cards): self._cards = list(cards) def __len__(self): return len(self._cards) def __getitem__(self, index): return self._cards[index]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class C: def __len__(self) -> int: ... def __getitem__(self, key): ... def __setitem__(self, key, value): ... def __delitem__(self, key): ... def __contains__(self, item) -> bool: ...
| Method | Used by |
|---|---|
__len__() |
len(obj). Also decides truthiness when __bool__() is missing: length 0 is false. |
__getitem__(key) |
obj[key], including slices (key is a slice object) and tuples (obj[1, 2]). |
__setitem__(key, value) |
obj[key] = value. |
__delitem__(key) |
del obj[key]. |
__contains__(item) |
item in obj. |
Return value: __len__() must return an integer greater than or equal to 0. The others return whatever suits the class.
Raises: by convention IndexError for a bad sequence index and KeyError for a missing mapping key. len() raises TypeError if __len__() returns a non-integer and ValueError if it is negative.
Usage notes
- Sequences vs mappings. Sequences accept integers (including negative ones) and slices and raise
IndexError; mappings accept any hashable key and raiseKeyError. - Slices arrive as
sliceobjects. Handle them withisinstance(index, slice)or by forwarding the key to an underlying list, which accepts slices itself. - Iteration fallback. If a class has no
__iter__()but has__getitem__(),fortries0, 1, 2, ...untilIndexError. This is whySquares()is iterable. Prefer a real__iter__()in new code. infallback. Without__contains__()Python uses__iter__(), then the__getitem__()fallback, which can be slow.- Reverse order.
reversed(obj)needs__len__()and__getitem__()(or__reversed__()). - Truthiness. An empty container is false, because
__len__()returns 0 (thebool(Playlist())line). - Inherit instead from
collections.abc.SequenceorMutableMappingto get many methods (index,count,get,items, ...) once you define the basic ones. - Missing keys on dict subclasses.
dictsubclasses can define__missing__();defaultdictuses it.
Related
len(),__iter__() and __next__(),reversed(),slice(),dictKeyError,IndexError- Lessons: Special methods, Slicing