My idea is to create specific function objects that can be added / subtracted / ... together, returning a new function object that has the same properties. This sample code hopefully demonstrates the idea:
from FuncObj import Func
quad = Func(lambda x: x**2)
cube = Func(lambda x: x**3)
plus = quad + cube
minus = quad - cube
other = quad * quad / cube
plus(1) + minus(32) * other(5)
I wrote the following code, which I hope will be commented and documented to explain what I want to achieve.
import operator
class GenericFunction(object):
""" Base class providing arithmetic special methods.
Use derived class which must implement the
__call__ method.
"""
def __add__(self, operand):
""" This is an example of a special method i want to implement. """
obj = GenericFunction()
obj.__class__ = type(obj.__class__.__name__, (obj.__class__,), {})
obj.__class__.__call__ = lambda s, ti: self(ti) + operand(ti)
return obj
def _method_factory(operation, name):
""" Method factory.
Parameters
----------
op : callable
an arithmetic operator from the operator module
name : str
the name of the special method that will be created
Returns
-------
method : callable
the __***__ special method
"""
def method(s, operand):
obj = GenericFunction()
obj.__class__ = type(obj.__class__.__name__, (obj.__class__,), {})
obj.__class__.__call__ = lambda s, ti: operation(s(ti), operand(ti))
return obj
return method
__sub__ = _method_factory(operator.__sub__, '__sub__')
__mul__ = _method_factory(operator.__mul__, '__mul__')
__truediv__ = _method_factory(operator.__truediv__, '__div__')
class Func(GenericFunction):
""" A customizable callable object.
Parameters
----------
func : callable
"""
def __init__(self, func):
self.func = func
def __call__(self, *args):
return self.func(*args)
if __name__ == '__main__':
quad = Func(lambda x: x**2)
cube = Func(lambda x: x**3)
poly_plus = quad + cube
poly_minus = quad - cube
assert quad(1) + cube(1) == poly_plus(1)
assert quad(1) - cube(1) == poly_minus(1)
I think something is missing from me, but I do not see it.
EDIT
After Dietrich’s answer, I forgot to mention the corner case. Suppose I want to subclass GenericInput, and I need to set up a method call without passing to the called constructor. I have examples (actually this is the code for which I originally posted this question).
class NoiseInput(GenericInput):
def __init__(self, sigma, a, b, t):
""" A band-pass noisy input. """
self._noise = lfilter(b, a, np.random.normal(0, 1, len(t)))
self._noise *= sigma/self._noise.std()
self._spline = InterpolatedUnivariateSpline(t, self._noise, k=2)
def __call__(self, ti):
""" Compute value of the input at a given time. """
return self._spline(ti)
class SineInput(GenericInput):
def __init__(self, A, fc):
self.A = A
self.fc = fc
def __call__(self, ti):
return self.A*np.sin(2*np.pi*ti*self.fc)
In this case, remains to be done.