ElectronicsStudent
ElectronicsStudent

Reputation: 222

Python: How to pass function with two parameters as an argument

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:

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!

Upvotes: 0

Views: 1034

Answers (2)

Alex
Alex

Reputation: 516

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):
        return 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

Upvotes: 1

rdas
rdas

Reputation: 21275

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)

Upvotes: 6

Related Questions