Home > Enterprise >  Python intrinsic types operator overloading
Python intrinsic types operator overloading

Time:09-22

Is there a way to overload operators for intrinsic types ?

Example: say I would like to overload the __mul__ operator for the function class:

def u(x): return cos(x)
def v(x): return sin(x)

w = u*v   # function x -> cos(x)*sin(x)

Sorry if I'm not using the right terminology.

CodePudding user response:

You cannot change built-in types, but you could write a wrapper class which behaves how you want:

class FuncWrapper:
    def __init__(self, f):
        self.f = f
    def __call__(self, x):
        return self.f(x)
    def __mul__(self, other):
        return FuncWrapper(lambda x: self(x) * other(x))

You can use it either directly, or as a decorator:

>>> from math import sin, cos
>>> sin, cos = FuncWrapper(sin), FuncWrapper(cos)
>>> (sin * cos)(1)
0.4546487134128409
>>> @FuncWrapper
... def func1(x):
...     return x   1
... 
>>> @FuncWrapper
... def func2(x):
...     return x   2
... 
>>> func3 = func1 * func2
>>> func3(5)
42

CodePudding user response:

One way to do this is symbolically using sympy

>>> import sympy
>>> x = sympy.Symbol('x')
>>> u = sympy.cos(x)
>>> v = sympy.sin(x)
>>> u
cos(x)
>>> v
sin(x)

Then

>>> w = u*v
>>> w
sin(x)*cos(x)
>>> w.subs(x, 0.5)
0.420735492403948
  • Related