I have been experimenting with the idea of function classes as explained in this article and Composition applied to function dependencies as described in the following questions:
Consider the following mathematical functions, where
x is a variable and
c are constants:
f(x) = a*x**2+b*x+c g(x) = a*sin(3*x)
As python function classes these can be expressed as follows:
import numpy as np class F: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __call__(self, x): return self.a*x**2+self.b*x+self.c class G: def __init__(self, a): self.a = a def __call__(self, x): return self.a*np.sin(3*x)
For several reasons which I prefer not to elaborate here, I prefer to have one meta class which can be instantiated and assigned any function. The difficulty is of course the constants as
self is undefined outside of a class. Here's what I mean:
def f(x): return a*x**2+b*x+c F = FunctionClass(f) #how to make a, b and c instance variables?
If I don't do this I am condemned to writing a class for every function, which defeats the purpose of what I am trying to achieve. I've asked a question addressing this on a more technical level in stack over flow but it was not very popular at all
Is there a design pattern or python construct that can allow me to achieve this? Perhaps decorators? Perhaps use of the
__dict__ attribute? Any ideas?