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() # from  w w w  . j  a  v a2 s  . c o  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() # 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:])

Result