I wanted to write M.det() instead of numpy.linalg.det(M),
so I did this:
numpy.matrix.det = numpy.linalg.det
and it worked.
Is there anything to be said against this proceeding?
Example:
import numpy as np
np.matrix.det = np.linalg.det
M = np.matrix([[1,2],[3,4]])
print M.det()
correct output: -2.0
This is called monkey patching. It may work in this special case, but it makes your program hard to follow since the det method only exists in your program and is not documented anywhere. Also, it relies on np.matrix implementation details, specifically that it is a pure Python class, and doesn't work for all classes:
>>> numpy.ndarray.det = numpy.linalg.det
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'numpy.ndarray'
I would advise against this; it makes your program harder to read and maintain and there's really no reason not to write from numpy.linalg import det, then det(A) instead of A.det().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With