Understand Python Callback Function for Beginners – Python Tutorial

By | July 13, 2019

Python callback function is an advanced tip for python programmers, which is very useful for streamlineding our code and application structure. In this tutorial, we will introduce how to use it.

python callback function

What is python callback function?

General speaking, python callback function is a function that can accept other functions as parameters.

Here we will use an example to help you understanding it.

Preliminaries

We create a function to compute 2*x.

def compute(x):
    return x*2

Create another function to accept a function name as parameter.

def listnum(x,f):
    return x + f(x)

In function listnum(x, f) , f parameter is a function name. listnum can accepte a function as its parameter.

Test python callback function

for i in range(10):
    x = 0
    if i % 2 == 0:
        x = listnum(i, compute)
    else:
        x = i
    print(x)

In this test code, we can find that function compute is passed into listnum as a parameter. Then you can get a result like:

0
1
6
3
12
5
18
7
24
9

To use python callback function, you must notice parameters of function which is called.

For example:

def listnum(x,f):
    return x + f(x)

In listnum function, f(x) is a function which is called in listnum function, which means that if a function ( f) can be used as a parameter of listnum, it must accept one parameter x. Otherwhile, it will not be used as a parameter of listnum.

For example:

def computeXY(x, y):
    return x+y

def listnum(x,f):
    return x + f(x)


for i in range(10):
    x = 0
    if i % 2 == 0:
        x = listnum(i, computeXY)
    else:
        x = i
    print(x)

In this code, computeXY accept two parameters, however, there only one parameter in f(x), which is in listnum(x, f).

So you will get error:

  File "e:\workspace-python\Y-MK\open-url.py", line 11, in listnum
    return x + f(x)
TypeError: computeXY() missing 1 required positional argument: 'y'

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *