Define `__getitem__` in a class to control what happens when an instance is accessed with subscription syntax. For an object `obj`, `obj[i]` invokes `obj.__getitem__(i)`. The method receives the index and returns the value to be accessed. section 17.7.1
An object with `__getitem__` can also be used in a `for` loop through successive accesses at indexes 0, 1, 2, and so on. Raising `IndexError` tells that loop to stop. This makes sequential access possible without storing every item in a list. section 17.7 section 17.7.1
class LineReader:
def __init__(self, filename):
self.fileobject = open(filename, 'r') #1
def __getitem__(self, index):
line = self.fileobject.readline() #2
if line == "": #3
self.fileobject.close() #4
raise IndexError #5
else:
return line.split("::")[:2] #6
for name, age in LineReader("filename"):
. . . do whatever . . .
`LineReader` reads one file line per access. It deliberately ignores the index, closes the file at the end, and raises `IndexError` to end the loop. section 17.7 section 17.7.1
Ignoring the index works for that narrow, sequential use; it does not provide general list behavior. An index-aware implementation can instead return an element from an underlying list. Other operations need their own special methods: `__setitem__`, for example, handles `obj[i] = value`. section 17.7.2 section 17.8
class TypedList:
def __init__(self, example_element, initial_list=[]):
self.type = type(example_element)
if not isinstance(initial_list, list):
raise TypeError("Second argument of TypedList must "
"be a list.")
for element in initial_list:
self.__check(element)
self.elements = initial_list[:]
def __check(self, element):
if type(element) != self.type:
raise TypeError("Attempted to add an element of "
"incorrect type to a typed list.")
def __setitem__(self, i, element):
self.__check(element)
self.elements[i] = element
def __getitem__(self, i):
return self.elements[i]
`TypedList.__getitem__` passes the index to its stored list, while `__setitem__` checks an element’s type before assignment. section 17.8

