左侧二元运算符的 numpy 强制问题
我正在实现一个类似数组的对象,它应该可以与标准 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 的 强制规则。更重要的是,它使我的左乘法变得毫无用处。
有人知道解决这个问题的方法吗?
(我认为 a 可以使用 __coerce__ 来修复它,但链接的文档解释说,不再调用该 a 来响应二元运算符......)
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...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明 numpy 为这个问题提供了一个简单的解决方案。以下代码按预期工作。
更多信息可以在此处找到。
It turns out that numpy offers a simple fix for this problem. The following code works as intended.
More information can be found here.