我想实现我自己的矩阵类,它继承自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)我真的对此一无所知,到目前为止,谷歌搜索也没有什么帮助。
谢谢!
发布于 2012-10-31 01:45:41
问得好!
从源代码上看,似乎np.matrix在__new__中设置了data参数,而不是在__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]]当然,出于其他原因,您可能需要一个子类。
https://stackoverflow.com/questions/13144512
复制相似问题