How to overload @ in python?
Asked Answered
I

1

2

I want to overload the operator @ in python for a class I have written. I know how to do operator overloading in general (i.e. by defining __add__ and __radd__ to overload +) but I could not find a way to overload @.

Why I know, that @ can be overloaded: for numpy arrays, A@B gives the matrix product of A and B, while A*B gives the Hadamard (element-wise) product.

Isaacson answered 17/3, 2022 at 12:2 Comment(0)
S
3

The methods you need to overload are the __matmul__ and __rmatmul__ methods. E.g. if you want to add the inner product to lists:

class Vector(list):
    def __matmul__(self, other):
        return sum(x * y for x, y in zip(self, other))

    def __rmatmul__(self, other):
        return self.__matmul__(other)

Stadler answered 17/3, 2022 at 12:17 Comment(1)
It is worth mentioning that this information is in the section on Special method names in the language reference.Hardship

© 2022 - 2024 — McMap. All rights reserved.