Luka Emon
Luka Emon

Reputation: 11

How to define a function that output another function?

I want to define a function that takes some arguments as input, and uses them to make another function, then outputs the new function.

For example:

makeIncrease(n) --> return a function that takes an argument, and return (argument + n)

applyIncrease(increaseFn, m) --> will apply increaseFn to argument m

So if I do this: applyIncrease(makeIncrease(n), m) --> will return m+n

How can I do it in python?

Upvotes: 0

Views: 146

Answers (2)

amey91
amey91

Reputation: 552

class Example:
    def result():
        def nestedResult(a,b):
            multiply = a*b
            return multiply
        return nestedResult  


    if __name__ == "__main__":
        x = result()
        print "multiplication_result:", x(1,10)

Upvotes: 0

Stephan
Stephan

Reputation: 3093

You can read about decorators in Python for more on this. For your specific question:

def applyIncrease(increaseFn, m):
    return increaseFn(m)

def makeIncrease(n):
    def _innerFn(arg):
        return arg + n
    return _innerFn

applyIncrease accepts a function and argument, and applies the function to the argument. makeIncrease accepts an argument n.

Let's say n=2 for the sake of an example. makeIncrease(2) returns a function that takes an argument and adds 2 to it.

Although I began _innerFn with an underscore, this is only a convention - the underscore is not required for the decorator to work.

Note also that functions are first class objects in Python, and that makeIncrease returns _innerFn and not _innerFn(). Return functions exactly as you would variables or object references - no parentheses.

Here are your functions in the interpreter. Note that the object reference wrapped_function refers to _innerFn, i.e. the return value of makeIncrease(2)

>>> wrapped_function = makeIncrease(2)
>>> wrapped_function
<function _innerFn at 0x100496758>
>>> total = applyIncrease(wrapped_function, 3)
>>> total
5

Upvotes: 4

Related Questions