将方法添加到 numpy 对象

Add method to numpy object

我有一个简单的问题。我想缩短克罗内克乘积的表达式

a=np.matrix('1 0; 0 1')
b=np.matrix('1 0; 0 1')
C=np.kron(a,b)

像这样

C=a.k(b)

我一直在鞭打 google 有一段时间了,但我并没有完全找到解决这个问题的办法。 我知道有一些解决方法可以很好地工作,但我想了解如何向这样的 numpy 对象添加一个函数。或任何对象。我想学,不想做。

有什么想法吗?提前致谢!

如果您不想子class Matrix,您可以在运行时修改您的方法。这意味着您只需创建要添加到矩阵 class 的函数,然后将其分配给您想要方法名称的 class 的属性名称,在本例中为 k.这是可行的,因为在 Python 中,函数首先是 class 对象,这意味着您可以将它们分配给一个变量(或 class 属性),这相当于在实际中定义函数class.

def kron(self, other):
    return np.kron(self, other)
    
np.matrix.k = kron

之后,您可以拨打:

>>> a.k(b)
matrix([[1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 1]])

您可以在这里阅读更多关于 monkeypatching 的信息:What is monkey patching?

我找到了答案

a=np.matrix('1 0; 0 1')
b=np.matrix('1 0; 0 1')

def k(self, b): # Have to add self since this will become a method
    return np.kron(self,b)
setattr(np.matrix, 'k', k)

print(a.k(b))

给我正确的结果。

Link 这对我有帮助: https://mgarod.medium.com/dynamically-add-a-method-to-a-class-in-python-c49204b85bd6