Home > Back-end >  Python: How to pass function with two parameters as an argument
Python: How to pass function with two parameters as an argument

Time:10-26

i have a problem:

I need to implement a function in python which prints a skalar multiple of an argument - the argument is a function itself which has the signature:

def innerF(a,b):
    return x

The skalar multiplier is a constant within the function - e.g.

return 55 * x

Now comes the part i dont seem to get: The call Sytanx is required to be:

print( outerF(innerF)(a,b))

So in summary

def innerF(a,b):
    return a   b

def outerF( #What goes here? ):
    return 55* #How two call the innerF?

print(outerF(innerF)(a,b))

What i know so far:

  • I can pass the innerF an the a,b as seperate arguments to outerF like

    def outerF(innerF,a,b): return 53* innerF(a,b)

What i dont get:

The signature of the outerF call with innerF(outerF)(a,b) is completly unknow to me. Also i could not find refernce.

Thank you very much in advance!

CodePudding user response:

outerF needs to return a function that is getting called with (a, b)

def innerF(a, b):
    return a   b


def outerF(func):
    # define a function to return
    def f(*args, **kwargs):
        # this just calls the given func & scales it
        return 55 * func(*args, **kwargs)

    return f


print(outerF(innerF)(1, 2))

Result:

165  # 55 * (1 2)

CodePudding user response:

So what you need is nested functions.

outerF(innerF)(a, b)

means outerF(innerF) returns a new function that then takes a and b as arguments.

To achieve this you need a function that returns a function.

def inner(a, b):
    return a   b

def outer(func):
    def wrapper(a, b):
        55 * func(a, b)
    return wrapper

outer(inner)(2, 3) # 275

You could also apply the outer function as a decorator.

@outer
def inner(a, b):
    return a   b
    
inner(2, 3) # 275
  • Related