I am confused as to when the __index__
method of a class is called. I had assumed the method would be called when ever the object was used in an indexing operation. I am not seeing __index__
called when the object is a subclass of int
.
In [1]: class foo(int):
...: def __new__(cls, value):
...: return int.__new__(cls, value)
...: def __index__(self):
...: return int(self)+1
In [2]: i=foo(0)
In [3]: i
Out[3]: 0
In [4]: i.__index__()
Out[4]: 1
In [5]: [0,1,2][:i.__index__()]
Out[5]: [0]
In [6]: [0,1,2][:i]
Out[6]: []
it appears that int(i)
is being used as the index not i.__index__()
. What have I misunderstood?
Edited to simplify and correct the example.