__index__ — Easy Examples
Returns an integer for use in slicing and bin()/hex()/oct()
Implementing __index__
Basic implementation of __index__ in a class.
python
class Example: def __index__(self): return "Example __index__" obj = Example() print(obj)
__index__ returns an integer for use in slicing and bin()/hex()/oct(). Implementing it lets you customize how Python interacts with your objects.
__index__ in action
Seeing __index__ called by Python's built-in operations.
python
# How Python calls __index__ automatically class Demo: def __init__(self, value): self.value = value def __index__(self): print(f"__index__ was called!") return self d = Demo(42) # This triggers __index__: print(d)
Python automatically calls __index__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground