简体   繁体   中英

Overriding __getitem__ on python

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.

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

return super().__getitem__(i) + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM