I have encountered a problem with the following code
def vdot(self, other):
return np.sum(self@other, axis=0)
np.array.vdot = vdot
This code should allow me to use the vdot function as
a=np.matrix('1 0; 0 1')
V=np.array([a,a,a])
print(V.vdot(V))
which should give me a 2x2 matrix, which is just 3 times the unit matrix. The code should just multiply vectors that have matrices as entries. Though, if I try do define this function with np.array.vdot = vdot, it gives me an error message "'builtin_function_or_method' object has no attribute 'vdot'". On the other hand, this works perfectly fine with matrices, see Add method to numpy object
Note that using vdot as vdot(array, array) works perfectly fine.
Why wouldn't this work on an array? Nothing seems to be different from the matrix case.
Thanks in advance :)
CodePudding user response:
The class you are looking for is np.ndarray
. np.array
is just a function that helps to instantiate ndarrays. But as you will see if you try to monkey patch np.ndarray, it's not possible. This is as far as I understand because the ndarray type is written and compiled in C and behaves like a built-in.