Я сделал ошибку при копировании из примера np.matrix
.
class Tuple(np.ndarray):
__array_priority__ = 10
def __new__(cls, input_array, info=None):
return np.asarray(input_array).view(cls)
class Matrix(np.ndarray):
__array_priority__ = 5.0
def __new__(cls, input_array, info=None):
return np.asarray(input_array).view(cls)
In [2]: def scaling(x, y, z):
...: ...: m = Matrix(np.identity(4))
...: ...: m[0, 0] = x
...: ...: m[1, 1] = y
...: ...: m[2, 2] = z
...: ...: return m
...:
In [3]: Tuple([1,2,3,4]) @ scaling(2,2,2)
Out[3]: Tuple([2., 4., 6., 4.])
In [4]: scaling(2,2,2) @ Tuple([1,2,3,4])
Out[4]: Tuple([2., 4., 6., 4.])
===
Получение подсказки из определения np.matrix
: numpy.matrixlib.defmatrix.py
Добавление атрибута __array_priority__
:
In [382]: class Tuple(np.ndarray):
...: def __new__(cls, input_array, info=None):
...: __array_priority = 10
...: return np.asarray(input_array).view(cls)
...:
...: class Matrix(np.ndarray):
...: def __new__(cls, input_array, info=None):
...: __array_priority = 5
...: return np.asarray(input_array).view(cls)
...:
In [383]:
In [383]: def scaling(x, y, z):
...: m = Matrix(np.identity(4))
...: m[0, 0] = x
...: m[1, 1] = y
...: m[2, 2] = z
...: return m
...:
In [384]: Tuple([1,2,3,4]) @ scaling(2,2,2)
Out[384]: Tuple([2., 4., 6., 4.])
In [385]: scaling(2,2,2) @ Tuple([1,2,3,4])
Out[385]: Matrix([2., 4., 6., 4.])