Раздел Data Model документации Python 3.2 предоставляет следующие описания для __int__
и __index__
методы:
object.__int__(self)
Названный для реализации встроенного [функция
int()
]. Должен возвратить [целое число].
object.__index__(self)
Названный к реализации
operator.index()
. Также названный каждый раз, когда для Python нужен целочисленный объект (такой как в разрезании, или во встроенномbin()
,hex()
иoct()
функции). Должен возвратить целое число.
Я понимаю, что они используются в различных целях, но я не мог выяснить, почему два различных метода необходимы. Каково различие между этими методами? Действительно ли безопасно просто исказить __index__ = __int__
в моих классах?
See PEP 357: Allowing Any Object to be Used for Slicing.
The
nb_int
method is used for coercion and so means something fundamentally different than what is requested here. This PEP proposes a method for something that can already be thought of as an integer communicate that information to Python when it needs an integer. The biggest example of why usingnb_int
would be a bad thing is that float objects already define thenb_int
method, but float objects should not be used as indexes in a sequence.
Edit: It seems that it was implemented in Python 2.5.
I believe you'll find the answer in PEP 357, which has this abstract:
This PEP proposes adding an nb_index slot in PyNumberMethods and an __index__ special method so that arbitrary objects can be used whenever integers are explicitly needed in Python, such as in slice syntax (from which the slot gets its name).