pythonpython-3.xoperatorscustom-operator

Allow python objects to interact with mathematical operators


I ask it because I remember numpy does it with arrays. I should add two objects that contain monomials.

Alternatively is it possible to create custom mathematical operators? (like the @ of numpy's dot product)


Solution

  • This is very possible. Classes can contain "magic methods" that can allow objects to interact with + and other operators. Specifically, this section of the documentation is relevant, although a quick read over that entire document would be quite helpful.

    The most relevant methods from that link:

    object.__add__(self, other)
    object.__sub__(self, other)
    object.__mul__(self, other)
    object.__matmul__(self, other)
    object.__truediv__(self, other)
    object.__floordiv__(self, other)
    object.__mod__(self, other)
    object.__divmod__(self, other)
    

    @ can, for example, be used by implementing a __matmul__ method:

    class T:
        def __matmul__(self, other_t):
            pass
    
    print(T() @ T())
    

    You cannot create "custom" operators that don't already exist in the language, but you can make use of any of the hooks into existing operators.