The Python Oracle

How to override the [] operator in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
00:22 Accepted answer (Score 420)
00:48 Answer 2 (Score 82)
01:20 Answer 3 (Score 22)
01:36 Thank you

--

Full question
https://stackoverflow.com/questions/1957...

Accepted answer links:
[__getitem__]: https://docs.python.org/reference/datamo...
[__setitem__]: https://docs.python.org/reference/datamo...

Answer 2 links:
http://docs.python.org/reference/datamod...

Answer 3 links:
http://docs.python.org/reference/datamod...

--

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