brg*_*rgn 6 python inheritance constructor numpy init
我想实现自己的矩阵类,它继承自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()
Run Code Online (Sandbox Code Playgroud)
因为我不断收到此错误,所以此代码中必定存在一个愚蠢的错误:
this_matrix = np.matrix()
TypeError: __new__() takes at least 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
我真的对此毫无头绪,谷歌搜索到目前为止没有帮助.
谢谢!
好问题!
从查看来源,似乎np.matrix设置了data参数__new__,而不是__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]]
Run Code Online (Sandbox Code Playgroud)
附录:您可能需要考虑使用工厂函数而不是子类来实现所需的行为.这将为您提供以下代码,这些代码更短更清晰,并且不依赖于__new__-vs- __init__实现细节:
def mymatrix():
return np.matrix('1 2; 3 4')
mat = mymatrix()
print mat
# outputs [[1 2] [3 4]]
Run Code Online (Sandbox Code Playgroud)
当然,出于其他原因,您可能还需要子类.
| 归档时间: |
|
| 查看次数: |
693 次 |
| 最近记录: |