Python: Using Classes to Implement a Matrix Addition Program

Document 对象参考手册Python3 Examples

We will use Python classes to implement a simple matrix addition program. Matrix addition requires that the two matrices have the same dimensions. We will create aMatrixclass, and implement the matrix addition method in it.

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 __add__(self, other):
        if self.rows != other.rows or self.cols != other.cols:
            raise ValueError("Matrices must have the same dimensions for addition.")

        result = [
            [self.data[i][j] + other.data[i][j] for j in range(self.cols)]
            for i in range(self.rows)
        ]
        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], [7, 8, 9]])
matrix2 = Matrix([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

result_matrix = matrix1 + matrix2
print(result_matrix)

Code analysis:

  1. __init__Method: Initializes the matrix object, accepting a two-dimensional listdataas input, and calculates the number of rows and columns of the matrix.
  2. __add__Method: Implements matrix addition. First, check whether the dimensions of the two matrices are the same; if not, raise an error. Then use list comprehension to add elements one by one and generate the result matrix.
  3. __str__Method: Converts the matrix to string format for easy printing.

Output result:

10 10 10
10 10 10
10 10 10

Document 对象参考手册Python3 Examples

Other Extensions