Fix Python – How to override the [] operator in Python?

Question

Asked By – Sahas

What is the name of the method to override the [] operator (subscript notation) for a class in Python?

Now we will see solution for issue: How to override the [] operator in Python?


Answer

You need to use the __getitem__ method.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

And if you’re going to be setting values you’ll need to implement the __setitem__ method too, otherwise this will happen:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

This question is answered By – David Webb

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0