Search code examples
python-3.xfunctionmathematical-optimizationmathematical-expressions

function with parameter that is a mathematical func


I'd like to have a function like this in Python:

class EvaluationStrategy(object):
    def __init__(self, test_function):

    self.test_function = test_function

class TestFunction(object):
    def objective_function(self, design_variable1, design_variable2):
        print("external function called")
        intermediate_results = self.__internal_function_evaluation_()

        v1= intermediate_results(0)
        v2= intermediate_results(2)

        v=test_function

After calling a function where EvaluationStrategy is contained, the testfunction e.g x^2 or something like that should be defined in dependence of x. But if x isn't defined Python always throws out an error so I tried it with lambda but it also doesn't work without defining x before. If anyone could please help me.Thanks in advance.


Solution

  • It is not clear what you are asking (see my comments), but it seems one of the ingredients you need is how to pass a function as an argument and store that function for later execution.

    Here is how you could do that:

    class EvaluationStrategy:
        def __init__(self, test_function):
            self.test_function = test_function
    
        def evaluate(self, arg):
            return self.test_function(arg)
    
    ev = EvaluationStrategy(lambda x: x**2)
    
    for i in range(2,5):
        print(i, ev.evaluate(i))