6

我想实现我自己的矩阵类,它继承自 numpy 的矩阵类。

numpy 的矩阵构造函数需要一个属性,例如("1 2; 3 4'"). 相反,我的构造函数应该不需要属性,并且应该为超级构造函数设置一个默认属性。

这就是我所做的:

import numpy as np

class MyMatrix(np.matrix):
    def __init__(self):
        super(MyMatrix, self).__init__("1 2; 3 4")

if __name__ == "__main__":
    matrix = MyMatrix()

这段代码一定有一个愚蠢的错误,因为我不断收到这个错误:

this_matrix = np.matrix()
TypeError: __new__() takes at least 2 arguments (1 given)

我对此一无所知,到目前为止,谷歌搜索也没有帮助。

谢谢!

4

1 回答 1

5

好问题!

从查看源代码来看,似乎np.matrixdata论点设置为 in __new__,而不是 in __init__。这是违反直觉的行为,尽管我确信这是有充分理由的。

无论如何,以下对我有用:

class MyMatrix(np.matrix):
    def __new__(cls):
        # note that we have to send cls to super's __new__, even though we gave it to super already.
        # I think this is because __new__ is technically a staticmethod even though it should be a classmethod
        return super(MyMatrix, cls).__new__(cls, "1 2; 3 4")

mat = MyMatrix()

print mat
# outputs [[1 2] [3 4]]

附录:您可能需要考虑使用工厂函数而不是子类来实现您想要的行为。这将为您提供以下代码,它更短更清晰,并且不依赖于__new__-vs-__init__实现细节:

def mymatrix():
    return np.matrix('1 2; 3 4')

mat = mymatrix()
print mat
# outputs [[1 2] [3 4]]

当然,您可能出于其他原因需要子类。

于 2012-10-30T17:45:41.087 回答