dimanche 15 mars 2020

Pass function to class instance and modify how the arguments are passed in the function

I'd like to build a class to which the user can pass a function. Once the user passes their custom function into this class, however, I'd like for the function to refer to instance variables rather than arguments provided in the function call. Here's an example of what I mean. The user could define a function as follows:

def f(x, a, b, c):
    return a*x**2+b*x+c

Once the user passes this function into an instance of my class, I'd like the function to be represented in the class as follows:

class Function:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    def __call__(self, x):
        return a*x**2+b*x+c

Where x is a variable and a, b and c are constants. I don't want the user to be burdened with making a class themselves.

Is there a way to do this in python?

Aucun commentaire:

Enregistrer un commentaire