Chapter 6: Higher order functions

Higher-order functions

face Josiah Wang

In Python, everything is an object (but you know this by now). Even functions are objects! Or more specifically, they are instances of the function class (or builtin_function_or_method for built-in functions).

>>> type(max)
<class 'builtin_function_or_method'>
>>> def my_function():
...    return 1
...
>>> type(my_function)
<class 'function'>
>>> type(my_function())
<class 'int'>

In Computer Science terms, Python functions are first class citizens, because they can be passed around and treated like any other objects.

In the code below, you can see that multiplier() actually accepts a function name as an input argument. In this example, we pass in laugh and cry (Lines 11-12). Note that you are passing the function name and not the function call (so no parenthesis () after the name). What is the output for the following piece of code? Take a guess, and verify by running it yourself!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def laugh():
    print("MUAHAHAHAHA!! :D")

def cry():
    print("WAAA!! TT_TT")      

def multiplier(func, repeats):
    for i in range(repeats):
        func()

multiplier(laugh, 5)
multiplier(cry, 2)

In mathematical terms, such functions are called higher-order functions. These are functions that take a function as an input argument or that return a function (we will discuss returning functions in one of the advanced lessons in the future).

Make sure you understand everything on this page before moving on. Otherwise it will get really confusing!