使用 __index__ 方法的 numpy ndarray 索引

numpy ndarray indexing with __index__ method

当使用自定义 class 实例作为索引时,我不明白 numpy ndarray 的索引是如何工作的。

我有以下代码:

import numpy as np

class MyClass:
    def __index__(self):
        return 1,2

foo = np.array([[1,2,3],[4,5,6]])
bar = MyClass()

print(foo[1,2])
print(foo[bar])

我希望从两个打印函数中得到相同的结果 (6)。但是从第二个开始,class 实例被用作索引,我收到一个错误:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

如果我使用

显式调用 __index__ 方法
print(foo[bar.__index__()])

有效。但这违背了魔术方法的目的。

如果我只用一个索引调用数组,一切正常:

import numpy as np

class MyClass:
    def __index__(self):
        return 1

foo = np.array([[1,2,3],[4,5,6]])
bar = MyClass()

print(foo[1])
print(foo[bar])

>>> [4 5 6]
>>> [4 5 6]

所以我没有得到:

是我漏掉了什么,还是 ndarray 不支持这种索引?


我只想补充一点,__index__ 方法如何输出结果显然无关紧要。我试过了:

return a, b
return (a, b)
return tuple((a, b))

None 其中对我有用。

如前所述here__index__方法Must return an integer.

这就是为什么您的尝试没有成功,而 "one index" 示例却成功了。