Special Method Protocols

__index__() — numeric protocol

Supply an exact integer for indexing, slicing and integer-only conversions. Implement only for integral concepts, not lossy conversion. The hook must return the specified numeric type. A fractional return value raises TypeError; do not truncate it in this hook.

Formal Syntax & Structure

python syntaxpython
def __index__(self):

Return Value

int

Converted numeric value.

Working Example

Example Snippetpython
import operatorclass Number:    def __init__(self, value):        self.value = value    def __index__(self):        return self.valueprint(operator.index(Number(3)))
Python Reference