Sahas Sahas - 1 year ago 102
Python Question

How to override [] operator

What is the name of the method to override the

operator for a class?

Answer Source

You need to use the __getitem__ method.

>>> class MyClass:
...     def __getitem__(self, key):
...         return key * 2
>>> myobj = MyClass()
>>> myobj[3]

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__'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download