__index__ method returns an integer value for an instance when needed.
It is used by built-ins that convert to digit strings and in retrospect, might have been better named __asindex__:
class C: def __index__(self): return 255 X = C() # from w w w . j a v a2 s . c o m print( hex(X) ) # Integer value print( bin(X) ) print( oct(X) )
It is also used in contexts that require an integer-including indexing:
class C: def __index__(self): return 255 X = C() # from w w w .j a v a2 s. c o m print( ('C' * 256)[255] ) print( ('C' * 256)[X] ) # As index (not X[i]) print( ('C' * 256)[X:] ) # As index (not X[i:])