Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override the [] operator in Python?

People also ask

Can [] operator be overloaded?

In the following example, a class called complx is defined to model complex numbers, and the + (plus) operator is redefined in this class to add two complex numbers. where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .

What does overloading the [] operator do?

The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.

Which function overloads the >> operator in Python?

7. Which function overloads the >> operator? Explanation: __rshift__() overloads the >> operator.

Which operator Cannot be overloaded in Python?

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well. Suppose we wanted to implement the less than symbol < symbol in our Point class.


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__'

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


You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6