How can we overload the @ operator?
I know that we can overload the +, *, etc. operators by implementing the __add__, __mul__, etc. methods, but what is the equivalent for @?
The @ operator was introduced in python 3.5 to facilitate matrix multiplication (see PEP 465 - A dedicated infix operator for matrix multiplication).
As indicated in the PEP definition, the @ operator can be overloaded using __matmul__ as it was initially introduced to perform matrix multiplication.
class foo:
def __init__(self, A):
self.A = A
def __matmul___(self, B):
# some operations on self.A and B
return ...
Like any other operator, you can overload its in place version @= using __imatmul__ as well as its reflected version with __rmatmul__.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With