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