1

I want to override the __getitem__ method on a class. I know there are similar questions, but I wanted to be more precise and clear. How do I make this work:

class A:
    def __init__(self, l: list): self.l = l
    def __getitem__(self, i: int): return self.l[i]

l = [1,2,3,4,5]
a = A(l)
a[3]
>> 4

So this works as expected, now I want to create class B that modifies the behaviour of __getitem__:

class B(A):
    def __getitem__(self, i: int):
        return super()[i]+1

b = B(l)
b[3]
>> ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-172-77fe0ff98a6a> in <module>
      1 b = B(l)
----> 2 b[3]

<ipython-input-165-7856a4b2c20b> in __getitem__(self, i)
      1 class B(A):
      2     def __getitem__(self, i):
----> 3         return super()[i]+1

TypeError: 'super' object is not subscriptable

Probably I am making a very silly mistake, but if I do the same thing with a method called f it works as expected.

1 Answer 1

4

You have to call the method explicitly on the super object, use:

return super().__getitem__(i) + 1
Sign up to request clarification or add additional context in comments.

1 Comment

WOW, so simple!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.