Python 矩阵算子&x2B;方法中的重载
我在理解(?)方法中的重载运算符是如何工作的方面有问题,有人能帮助我并告诉我如何重载下面的方法(即运算符+)Python 矩阵算子&x2B;方法中的重载,python,matrix,methods,operator-overloading,overloading,Python,Matrix,Methods,Operator Overloading,Overloading,我在理解(?)方法中的重载运算符是如何工作的方面有问题,有人能帮助我并告诉我如何重载下面的方法(即运算符+) 如果要为自定义类型定义+-运算符(在本例中为类MyMatrix),只需将其实现为相应类(MyMatrix)的方法,并为所述方法使用相应的名称。对于+运算符,此名称为\uuuuuuuuuuuuuuuuuuuuuu,(请参阅) 所以在你的情况下,你必须写作 class MyMatrix: def __add__(self, mat2): mat1 = self
如果要为自定义类型定义
+
-运算符(在本例中为类MyMatrix
),只需将其实现为相应类(MyMatrix
)的方法,并为所述方法使用相应的名称。对于+
运算符,此名称为\uuuuuuuuuuuuuuuuuuuuuu
,(请参阅)
所以在你的情况下,你必须写作
class MyMatrix:
def __add__(self, mat2):
mat1 = self
if mat1.height != mat2.height or mat1.width != mat2.width:
print("The matrices are not the same size!")
return
rows = []
for i in range(len(mat1.data)):
row = []
for j in range(len(mat1.data[0])):
row.append(mat1[i][j] + mat2[i][j])
rows.append(tuple(row))
return MyMatrix(tuple(rows))
class MyMatrix:
def __add__(self, mat2):
mat1 = self
if mat1.height != mat2.height or mat1.width != mat2.width:
print("The matrices are not the same size!")
return
rows = []
for i in range(len(mat1.data)):
row = []
for j in range(len(mat1.data[0])):
row.append(mat1[i][j] + mat2[i][j])
rows.append(tuple(row))
return MyMatrix(tuple(rows))