Python - Integer value:__index__

Introduction

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

Demo

class C: 
    def __index__(self): 
        return 255 

X = C() # w w  w  . j  av  a2s .co  m
print( hex(X) )               # Integer value 
print( bin(X) )
print( oct(X) )

Result

It is also used in contexts that require an integer-including indexing:

Demo

class C: 
    def __index__(self): 
        return 255 

X = C() #   ww w.j a v a 2s .  co m
print( ('C' * 256)[255] ) 
print( ('C' * 256)[X] )       # As index (not X[i]) 
print( ('C' * 256)[X:] )      # As index (not X[i:])

Result