Python Create a Class to Perform Matrix Multiplication with a Custom Method

Document 对象参考手册Python3 Examples

We will create a class namedMatrixwhich contains a custom methodmultiplyfor performing matrix multiplication. Matrix multiplication requires that the number of columns in the first matrix equals the number of rows in the second matrix.

Example

class Matrix:
    def __init__(self, data):
        self.data = data
        self.rows = len(data)
        self.cols = len(data[0]) if self.rows > 0 else 0

    def multiply(self, other):
        if self.cols != other.rows:
            raise ValueError("The number of columns in the first matrix must be equal to the number of rows in the second matrix.")

        result = [[0 for _ in range(other.cols)] for _ in range(self.rows)]

        for i in range(self.rows):
            for j in range(other.cols):
                for k in range(self.cols):
                    result[i][j] += self.data[i][k] * other.data[k][j]

        return Matrix(result)

    def __str__(self):
        return 'n'.join([' '.join(map(str, row)) for row in self.data])

# Example usage
matrix1 = Matrix([[1, 2, 3], [4, 5, 6]])
matrix2 = Matrix([[7, 8], [9, 10], [11, 12]])

result_matrix = matrix1.multiply(matrix2)
print(result_matrix)

Code analysis:

  1. __init__The method is used to initialize the matrix object, accepting a two-dimensional listdataas a parameter, and calculates the number of rows and columns of the matrix.
  2. multiplyThe method is used to perform matrix multiplication. First, it checks whether the number of columns in the first matrix equals the number of rows in the second matrix. If they are not equal, an exception is raised. Then, a result matrix is created, and a triple loop is used to calculate the value of each element.
  3. __str__The method is used to convert the matrix object into a string form for easy printing.
  4. In the example, two matrices are createdmatrix1andmatrix2, and callsmultiplythe method to perform matrix multiplication, and finally prints the result.

Output result:

58 64
139 154

Document 对象参考手册Python3 Examples

Other Extensions