ger*_*jan 5 python numpy coercion
我正在实现一个类似数组的对象,它应该可以与标准的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()
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:
[<__main__.MyArray instance at 0x91903ec>
<__main__.MyArray instance at 0x919038c>
<__main__.MyArray instance at 0x919042c>]
Run Code Online (Sandbox Code Playgroud)
很明显,不是MyArray().__rmul__( array([1,2,3]) )像我希望的那样调用,而是调用__rmul__数组的每个元素,并将结果包装在一个对象数组中.这在我看来不符合python的强制规则.更重要的是,它使我的左乘法无用.
有人知道解决这个问题吗?
(我认为可以使用它修复它,__coerce__但是链接文档解释了为了响应二元运算符而不再调用它...)
事实证明 numpy 为这个问题提供了一个简单的解决方案。以下代码按预期工作。
class MyArray( object ):
__array_priority__ = 1. # <- fixes the problem
def __rmul__( self, other ):
return MyArray()
Run Code Online (Sandbox Code Playgroud)
更多信息可以在这里找到。
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |