Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload "@" operator in python?

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 @?

like image 418
BiBi Avatar asked Oct 31 '25 01:10

BiBi


1 Answers

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__.

like image 101
BiBi Avatar answered Nov 01 '25 16:11

BiBi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!