all Python 3OOPfunction
__getitem__
magic methods
The method behind indexing: obj[k] calls obj.__getitem__(k). A slice arrives as a slice object.
Syntax
def __getitem__(self, key): ...
A __getitem__ with integer indexes is enough to make an object iterable: for walks 0, 1, 2… until IndexError. Mappings conventionally raise KeyError and sequences IndexError — dict.get and iteration rely on that difference. obj[1:3] passes slice(1, 3, None).
Examples
class Squares:
def __getitem__(self, i):
if i >= 5:
raise IndexError(i)
return i * i
s = Squares()
print(s[3]) # → 9
print(list(s)) # → [0, 1, 4, 9, 16] — итерация через __getitem__
class Show:
def __getitem__(self, key):
return key
print(Show()[1:3]) # → slice(1, 3, None)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy