@ 操作符
正在定义一个称为矩阵的类,并且将定义一个执行矩阵乘法的方法。
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def __matmul__(self, other):
return Matrix(
[
[
sum(a * b for a, b in zip(row_a, col_b))
for col_b in zip(*other.matrix)
]
for row_a in self.matrix
]
)
def __str__(self):
return "\n".join(["\t".join(map(str, row)) for row in self.matrix])
m = Matrix([[1, 2], [3, 4]])
n = Matrix([[5, 6], [7, 8]])
print(m @ n)
19 22
43 50
也可以将它用作任何其他二元运算符。
class A:
def __init__(self, num):
self.num = num
def __matmul__(self, other):
return A(self.num + other.num)
def __str__(self):
return f"A({self.num})"
a = A(10)
b = A(20)
c = a @ b
print(c)
A(30)
结论
Python 中的 @ 运算符与实现 __matmul__ 方法的类一起使用时,提供了一种为对象定义自定义操作的强大方法。
通过定义 __matmul__ ,可以指定使用 @ 运算符时类的实例如何与其他对象交互。这对于实现矩阵乘法(如示例中所示)或定义涉及两个对象的其他类型的运算非常有用。