预计阅读本页时间:-
Indexing and Slicing: __getitem__ and __setitem__
If defined in a class (or inherited by it), the __getitem__ method is called automatically for instance-indexing operations. When an instance X appears in an indexing expression like X[i], Python calls the __getitem__ method inherited by the instance, passing X to the first argument and the index in brackets to the second argument. For example, the following class returns the square of an index value:
>>> class Indexer:
... def __getitem__(self, index):
... return index ** 2
...
>>> X = Indexer()
>>> X[2] # X[i] calls X.__getitem__(i)
4
>>> for i in range(5):
... print(X[i], end=' ') # Runs __getitem__(X, i) each time
...
0 1 4 9 16