Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 矩阵算子&x2B;方法中的重载_Python_Matrix_Methods_Operator Overloading_Overloading - Fatal编程技术网

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