我很困惑 __index__
何时出现调用类的方法。我假设当在索引操作中使用该对象时就会调用该方法。我没有看到__index__
当对象是 int
的子类时调用。
In [1]: class foo(int):
...: def __new__(cls, value):
...: return int.__new__(cls, value)
...: def __index__(self):
...: return int(self)+1
In [2]: i=foo(0)
In [3]: i
Out[3]: 0
In [4]: i.__index__()
Out[4]: 1
In [5]: [0,1,2][:i.__index__()]
Out[5]: [0]
In [6]: [0,1,2][:i]
Out[6]: []
看起来 int(i)
被用作索引而不是 i.__index__()
。我误解了什么?
进行编辑以简化和更正示例。
最佳答案
__index__
实现无损转换为int
。 Python仅调用__index__
如果它确实需要这样的转换。就您而言,它不需要转换,因为您的 i
已经是一个 int 了。 Python只是直接使用int值。
如果您想查看处理此问题的代码,它位于 PyNumber_Index
下.
关于Python 3.5 : subclasses of int don't call the __index__ method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524453/