0

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 :)

trincot
  • 317,000
  • 35
  • 244
  • 286
Leviathan
  • 181
  • 6
  • are you sure its is not because you are not using the transpose of V like: V.vdot(V.T) ? – Guinther Kovalski Dec 02 '21 at 12:39
  • Hi, no. The function cannot even be defined. The line "np.array.vdot = vdot" gives an error, meaning, before I get to use it. Also, the code works without transposing the vector. – Leviathan Dec 02 '21 at 12:58
  • `np.array` is function. You can't add attributes or methods to a function. – hpaulj Dec 02 '21 at 16:30
  • `type(np.matrix)` gives `` but `type(np.array)` gives ``. there is ndarray and `type(ndarray)` also gives `` but if you try to assign function then it shows `built-in/extension type 'numpy.ndarray'` and it can means code in C/C++ and it can't have extensions like this. – furas Dec 02 '21 at 16:38
  • 1
    `np.matrix` is a subclass definition written in python. Thus is has a `__dict__` and can take additional methods as you did. `np.array` is a compiled function that returns a `ndarray` object. The `ndarray` class code is all compiled, and does not have this directory, so you can't add methods or attributes to numpy arrays. numpy.matrixlib.defmatrix.py` is the `matrix` source code. – hpaulj Dec 02 '21 at 17:24
  • The best you can do from my point of view is to wrap-up the np.array in class and make a custom method for your case. – Guinther Kovalski Dec 02 '21 at 18:02
  • @furas Thanks. I did not know the command type(). It wasn't obvious to me what the 'type' in means, but I found this https://realpython.com/python-metaclasses/, from where I understood that 'type' is just the "default type" of a class (rather than something more obvious like ). – Leviathan Dec 03 '21 at 15:20

1 Answers1

4

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.

sunnytown
  • 1,844
  • 1
  • 6
  • 13