Hi Pythonistas!
We know @ operator is used for decorator, But there is another usage of @ operator i have recently learned. In this post we will learn about Matrix multiplication operators. The @ operator was introduced in PEP 465 (Python 3.5+) to provide a dedicated syntax for matrix multiplication, making code more readable and concise.
code
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = A @ B
print(result)
Output:
[[19 22]
[43 50]]
This is equivalent to using np.dot(A, B) or A.dot(B), but the @ operator is cleaner and preferred for matrix multiplication.
Usage in Custom Classes
You can also define the behavior of the @ operator for your own classes by implementing the __matmul__ methods.
code
class Matrix:
def __init__(self, data):
self.data = data
def __matmul__(self, other):
result = [[sum(a * b for a, b in zip(row, col)) for col in zip(*other.data)] for row in self.data]
return Matrix(result)
def __repr__(self):
return f"{self.data}"
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 6], [7, 8]])
result = A @ B
print(result)
Output:
[[19, 22], [43, 50]]
Matrix Multiplication: The @ operator is primarily used for matrix multiplication.
Custom Implementation: You can define the __matmul__ method to customize its behavior for your own classes.
Not for Scalars or Element-wise Operations: The @ operator is strictly for matrix multiplication. For element-wise operations, use * instead.
I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in