简体   繁体   English

Python 3.5:int的子类不会调用__index__方法吗?

[英]Python 3.5: subclasses of int don't call the __index__ method?

I am confused as to when the __index__ method of a class is called. 我对何时调用类的__index__方法感到困惑。 I had assumed the method would be called when ever the object was used in an indexing operation. 我曾假设在索引操作中使用过该对象时将调用该方法。 I am not seeing __index__ called when the object is a subclass of int . 当对象是int的子类时,我没有看到__index__被调用。

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]: []

it appears that int(i) is being used as the index not i.__index__() . 似乎int(i)被用作索引而不是i.__index__() What have I misunderstood? 我误会了什么?

Edited to simplify and correct the example. 编辑以简化和纠正示例。

__index__ implements lossless conversion to int . __index__实现无损转换为int Python only calls __index__ if it actually needs such a conversion. Python仅在确实需要这种转换时才调用__index__ In your case, it doesn't need a conversion, because your i is already an int. 就您而言,它不需要转换,因为您的i已经是一个int。 Python just uses the int value directly. Python只是直接使用int值。

If you want to see the code that handles this, it's under PyNumber_Index . 如果要查看处理此问题的代码,则在PyNumber_Index下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM