How to override the [] operator in Python?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 How To Override The [] Operator In Python?
00:14 Accepted Answer Score 457
00:39 Answer 2 Score 24
00:53 Answer 3 Score 90
01:19 Thank you
--
Full question
https://stackoverflow.com/questions/1957...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #operatoroverloading
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 How To Override The [] Operator In Python?
00:14 Accepted Answer Score 457
00:39 Answer 2 Score 24
00:53 Answer 3 Score 90
01:19 Thank you
--
Full question
https://stackoverflow.com/questions/1957...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #operatoroverloading
#avk47
ACCEPTED ANSWER
Score 457
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__'
ANSWER 2
Score 90
To fully overload it you also need to implement the __setitem__and __delitem__ methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__.
There are all documented in http://docs.python.org/reference/datamodel.html
ANSWER 3
Score 24
You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6