【问题标题】:Python 3.5: subclasses of int don't call the __index__ method?Python 3.5:int 的子类不调用 __index__ 方法?
【发布时间】:2019-02-04 21:19:05
【问题描述】:

我对何时调用类的__index__ 方法感到困惑。我曾假设在索引操作中使用对象时会调用该方法。当对象是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]: []

似乎int(i) 被用作索引而不是i.__index__()。我误会了什么?

经过编辑以简化和更正示例。

【问题讨论】:

  • 你没有误会什么。
  • data model docs中的注释
  • " 为了有一个一致的整数类型类,当定义 __index__() 时,还应该定义 __int__(),并且两者都应该返回相同的值。"看来你现在有问题
  • @Jean-François Fabre 是的,我现在确实有问题,谢谢大家。

标签: python python-3.x


【解决方案1】:

__index__ 实现到int 的无损转换。如果 Python 确实需要这样的转换,它只会调用 __index__。在您的情况下,它不需要转换,因为您的 i 已经是一个 int。 Python 只是直接使用 int 值。

如果您想查看处理此问题的代码,请参阅PyNumber_Index

【讨论】:

    猜你喜欢
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多