Numpy Matrix class: Default constructor attributes for inherited class

不想你离开。 提交于 2019-12-01 18:12:19

Good question!

From looking at the source, it seems as though np.matrix sets the data argument in __new__, not in __init__. This is counterintuitive behaviour, though I'm sure there's a good reason for it.

Anyway, the following works for me:

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]]

Addendum: you might want to consider using a factory function, rather than a subclass, for the behaviour you want. This would give you the following code, which is much shorter and clearer, and doesn't depend on the __new__-vs-__init__ implementation detail:

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

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

Of course, you might need a subclass for other reasons.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!