Python中@=符号的作用是什么?已查阅分隔符文档仍存疑
@= operator mean in Python? Hey there! Let's clear up what the @= operator does in Python, since the delimiters doc might just list it without diving into details.
First off, @= is the matrix multiplication assignment operator, introduced back in Python 3.5 alongside the standalone @ matrix multiplication operator. It combines two actions in one step: performing matrix multiplication between the left and right operands, then assigning the result back to the left variable.
Breakdown of how it works:
- The
@operator itself is used for matrix-style multiplication. It works on any objects that implement the__matmul__special method (like NumPy arrays, pandas DataFrames, or custom matrix classes you define). @=is shorthand fora = a @ b, but with a small caveat: if the left operand implements the__imatmul__special method (the in-place version of__matmul__), it will modify the object in place instead of creating a new one. This is similar to how+=works compared toa = a + b.
Example with NumPy arrays (the most common use case):
import numpy as np # Define two 2x2 matrices matrix_a = np.array([[1, 2], [3, 4]]) matrix_b = np.array([[5, 6], [7, 8]]) # Use @= to perform matrix multiplication and assign back to matrix_a matrix_a @= matrix_b print(matrix_a) # Output: # [[19 22] # [43 50]]
Example with a custom matrix class:
If you're building your own matrix type, you can implement the special methods to support @=:
class SimpleMatrix: def __init__(self, values): self.values = values # Implement standard matrix multiplication for @ def __matmul__(self, other): # Simplified for 2x2 matrices a11, a12 = self.values[0] a21, a22 = self.values[1] b11, b12 = other.values[0] b21, b22 = other.values[1] new_values = [ [a11*b11 + a12*b21, a11*b12 + a12*b22], [a21*b11 + a22*b21, a21*b12 + a22*b22] ] return SimpleMatrix(new_values) # Implement in-place matrix multiplication for @= def __imatmul__(self, other): result = self @ other self.values = result.values return self def __repr__(self): return str(self.values) # Test it out m1 = SimpleMatrix([[1, 2], [3, 4]]) m2 = SimpleMatrix([[5, 6], [7, 8]]) m1 @= m2 print(m1) # Output: [[19, 22], [43, 50]]
Why the delimiters doc doesn't explain it:
The official delimiters reference just lists all the symbols Python recognizes as delimiters/operators, but the detailed behavior of each operator is covered in other sections of the Python docs—like the Data Model section (which covers special methods) or the Expressions chapter (which breaks down operator behavior).
内容的提问来源于stack exchange,提问作者user2467011

