Her*_*nan 7 python arrays numpy matrix subclassing
我试图将numpy ndarray子类化,但是我无法使用其他numpy类型(如masked array或matrix)进行操作.在我看来,__ array_priority__没有被尊重.作为一个例子,我创建了一个模拟重要方面的虚拟类:
import numpy as np
class C(np.ndarray):
__array_priority__ = 15.0
def __mul__(self, other):
print("__mul__")
return 42
def __rmul__(self, other):
print("__rmul__")
return 42
Run Code Online (Sandbox Code Playgroud)
我的类和普通 ndarray 之间的操作按预期工作:
>>> c1 = C((3, 3))
>>> o1 = np.ones((3, 3))
>>> print(o1 * c1)
__mul__
42
>>> print(c1 * o1)
__rmul__
42
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用矩阵(或掩码数组)时,不尊重数组优先级.
>>> m = np.matrix((3, 3))
>>> print(c1 * m)
__mul__
42
>>> print(m * c1)
Traceback (most recent call last):
...
File "/usr/lib64/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 330, in __mul__
return N.dot(self, asmatrix(other))
ValueError: objects are not aligned
Run Code Online (Sandbox Code Playgroud)
在我看来,ufuncs包装矩阵和掩码数组的方式不支持数组优先级.是这样的吗?有解决方法吗?
一种解决方法是子类化np.matrixib.defmatrix.matrix:
class C(np.matrixlib.defmatrix.matrix):
__array_priority__ = 15.0
def __mul__(self, other):
print("__mul__")
return 42
def __rmul__(self, other):
print("__rmul__")
return 4
Run Code Online (Sandbox Code Playgroud)
在这种情况下,优先级也高于 anp.ndarray并且始终调用您的乘法方法。
正如注释中所添加的,如果需要互操作性,您可以从多个类进行子类化:
class C(np.matrixlib.defmatrix.matrix, np.ndarray):
Run Code Online (Sandbox Code Playgroud)