简体   繁体   中英

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 - eg

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!

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM