[Python] Python __index__ special method

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    >>> class Thing(object):
    ... def __index__(self):
    ... return 1
    ...
    >>> thing = Thing()
    >>> list_ = ['abc', 'def', 'ghi']
    >>> list_[thing]
    'def'
    >>> dict_ = {1: 'potato'}
    >>> dict_[thing]
    # KeyError


    How does thing know to represent itself as 1 when accessed by a list, but not by a dict? Don't both magic methods go through __getitem__? The usage shown for lists could go through __int__ instead so what is the raison d'être for __index__ anyway?

    Continue reading...

Compartilhe esta Página