5

我正在实现一个类似数组的对象,它应该可以与标准的 numpy 数组互操作。我刚刚遇到了一个恼人的问题,它缩小到以下问题:

class MyArray( object ):
  def __rmul__( self, other ):
    return MyArray() # value not important for current purpose

from numpy import array
print array([1,2,3]) * MyArray()

这会产生以下输出:

[<__main__.MyArray instance at 0x91903ec>
 <__main__.MyArray instance at 0x919038c>
 <__main__.MyArray instance at 0x919042c>]

显然,不是MyArray().__rmul__( array([1,2,3]) )像我希望的那样调用,而是__rmul__为数组的每个单独元素调用,并将结果包装在一个对象数组中。在我看来,这似乎不符合 python 的强制规则。更重要的是,它使我的左乘法无用。

有人知道解决这个问题的方法吗?

(我认为可以使用它来修复它,__coerce__但链接的文档解释说,不再调用它来响应二元运算符......)

4

1 回答 1

1

事实证明,numpy 为这个问题提供了一个简单的解决方案。以下代码按预期工作。

class MyArray( object ):
  __array_priority__ = 1. # <- fixes the problem
  def __rmul__( self, other ):
    return MyArray()

更多信息可以在这里找到。

于 2011-08-14T14:57:33.613 回答