How to override the  operator in Python?
You need to use the
class MyClass: def __getitem__(self, key): return key * 2myobj = MyClass()myobj #Output: 6
And if you're going to be setting values you'll need to implement the
__setitem__ method too, otherwise this will happen:
5] = 1Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: MyClass instance has no attribute '__setitem__'myobj[
To fully overload it you also need to implement the
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
You are looking for the
__getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6