Calmcode - decorators: functions

Functions

1 2 3 4 5 6 7 8 9 10

In python, functions can accept functions as input. This might seems a bit strange at first so let's look at an example.

def apply(func, a, b):
    return func(a, b)

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

apply(add, 1, 2), apply(sub, 1, 2)

But they can also return functions as output.

def power(n):
    def func(number):
        return number**n
    return func

pow2 = power(2)
pow3 = power(3)

pow2(3), pow3(3)