Python - Indexing: __getitem__ and __setitem__

Introduction

Indexing and Slicing: __getitem__ and __setitem__ methods allow your classes to mimic some of the behaviors of sequences and mappings.

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.

Demo

class Indexer: 
    def __getitem__(self, index): 
        return index ** 2 

X = Indexer() # from   ww  w .jav  a 2s.  c om
X[2]                                # X[i] calls X.__getitem__(i) 
for i in range(5): 
    print(X[i], end=' ')            # Runs __getitem__(X, i) each time