0

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?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Luka Emon
  • 11
  • 1

2 Answers2

4

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
Stephan
  • 2,863
  • 1
  • 17
  • 14
  • Thanks you~ I just begin to understand the power of python. Take function as first class citizen is really expressive and intuitive for me to program. – Luka Emon Jul 29 '14 at 18:35
  • Guess I need to know more coding conventions to participate open source project, because I do see lots of underscore.... I don't know how to interpret them XD. – Luka Emon Jul 29 '14 at 18:36
  • There are some good answers on the underscore on [this question](http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python). You will see a lot of underscores in open source, especially double underscores, another useful convention. Please accept my answer if it was useful! – Stephan Jul 29 '14 at 22:08
0
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)
amey91
  • 542
  • 6
  • 17