Python 实现一个基于类的矩阵类
我们将创建一个基于类的矩阵类,这个类将支持矩阵的初始化、矩阵的加法、矩阵的乘法以及矩阵的转置操作。这个类将帮助我们理解如何在 Python 中使用类来封装数据和操作。
实例
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 __mul__(self, other):
if self.cols != other.rows:
raise ValueError("Number of columns in the first matrix must be equal to the number of rows in the second matrix.")
result = [[sum(self.data[i][k] * other.data[k][j] for k in range(self.cols)) for j in range(other.cols)] for i in range(self.rows)]
return Matrix(result)
def transpose(self):
result = [[self.data[j][i] for j in range(self.rows)] for i in range(self.cols)]
return Matrix(result)
def __str__(self):
return 'n'.join([' '.join(map(str, row)) for row in self.data])
# 示例使用
m1 = Matrix([[1, 2], [3, 4]])
m2 = Matrix([[5, 6], [7, 8]])
print("Matrix 1:")
print(m1)
print("Matrix 2:")
print(m2)
print("Matrix 1 + Matrix 2:")
print(m1 + m2)
print("Matrix 1 * Matrix 2:")
print(m1 * m2)
print("Transpose of Matrix 1:")
print(m1.transpose())
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 __mul__(self, other):
if self.cols != other.rows:
raise ValueError("Number of columns in the first matrix must be equal to the number of rows in the second matrix.")
result = [[sum(self.data[i][k] * other.data[k][j] for k in range(self.cols)) for j in range(other.cols)] for i in range(self.rows)]
return Matrix(result)
def transpose(self):
result = [[self.data[j][i] for j in range(self.rows)] for i in range(self.cols)]
return Matrix(result)
def __str__(self):
return 'n'.join([' '.join(map(str, row)) for row in self.data])
# 示例使用
m1 = Matrix([[1, 2], [3, 4]])
m2 = Matrix([[5, 6], [7, 8]])
print("Matrix 1:")
print(m1)
print("Matrix 2:")
print(m2)
print("Matrix 1 + Matrix 2:")
print(m1 + m2)
print("Matrix 1 * Matrix 2:")
print(m1 * m2)
print("Transpose of Matrix 1:")
print(m1.transpose())
代码解析:
__init__
方法用于初始化矩阵对象,接受一个二维列表作为参数,并计算矩阵的行数和列数。__add__
方法实现了矩阵的加法操作,首先检查两个矩阵的维度是否相同,然后逐个元素相加,返回一个新的矩阵对象。__mul__
方法实现了矩阵的乘法操作,首先检查第一个矩阵的列数是否等于第二个矩阵的行数,然后进行矩阵乘法运算,返回一个新的矩阵对象。transpose
方法实现了矩阵的转置操作,返回一个新的转置矩阵对象。__str__
方法用于将矩阵对象转换为字符串形式,便于打印输出。
输出结果:
Matrix 1: 1 2 3 4 Matrix 2: 5 6 7 8 Matrix 1 + Matrix 2: 6 8 10 12 Matrix 1 * Matrix 2: 19 22 43 50 Transpose of Matrix 1: 1 3 2 4
点我分享笔记