开发者

numpy coercion problem for left-sided binary operator

I am implementing an array-like object that should be interoperable with standard numpy arrays. I just hit an annoying problem that narrows down to the following:

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()

This yields the following output:

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

Clearly, rather than calling MyArray().__rmul__( array([1,2,3]) ) as I had hoped, __rmul__ is called for every individual element of 开发者_开发百科the array, and the result wrapped in an object array. This seems to me non compliant with python's coercion rules. More importantly, it renders my left multiplication useless.

Does anybody know a way around this?

(I thought a could fix it using __coerce__ but the linked document explains that that one is no longer invoked in response to binary operators...)


It turns out that numpy offers a simple fix for this problem. The following code works as intended.

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

More information can be found here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜