Python __getitem__: Adding bracket notation to your classes

Python __getitem__: Adding bracket notation to your classes

Want your Python object to support bracket notation []? Define __getitem__:

class MyList:
    def __init__(self, items):
        self.items = items
    def __getitem__(self, i):
        return self.items[i]
m = MyList([1,2,3])
m[0]  # returns 1