Home >Backend Development >Python Tutorial >What is a callback function?

What is a callback function?

零下一度
零下一度Original
2017-06-28 16:16:371057browse

What is a callback function?


Let’s take a long way to answer this question.

Programming is divided into two categories: system programming and application programming. The so-called system programming, simply put, is to write libraries; and application programming is to use various written libraries to write programs with certain functions, that is, applications. System programmers will leave some interfaces, namely API (application programming interface, application programming interface), for the libraries they write for use by application programmers. So in the abstraction layer diagram, the library is underneath the application.

When the program runs, under normal circumstances, the application program (application program) will often call pre-prepared functions in the library through the API. However, some library functions require the application to pass it a function first, so that it can be called at the appropriate time to complete the target task. The function that is passed in and called later is called the callback function.

For example, a hotel provides a wake-up service, but requires travelers to decide how to wake up. You can call the guest room, you can send a waiter to knock on the door, or you can ask for water to be poured on your head if you are so sleepy that you are afraid of delaying things. Here, the "wake up" behavior is provided by the hotel, which is equivalent to a library function, but the method of waking up is decided by the passenger and told to the hotel, which is a callback function. The action of the passenger telling the hotel how to wake him up, that is, the action of passing the callback function into the library function, is called to register a callback function. As shown in the figure below (image source: Wikipedia):


As you can see, the callback function is usually at the same abstraction layer as the application (because what kind of callback function is passed in is determined at the application level) . The callback becomes a process in which the higher layer calls the lower layer, and the lower layer then calls the higher layer. (I think) This should be the earliest application of callbacks, and the reason why they are named so.

Advantages of the callback mechanism

As can be seen from the above example, the callback mechanism provides great flexibility. Please note that from now on, we refer to the library functions in the diagram as intermediate functions. This is because callbacks are not only used between the application and the library. Anytime you want flexibility similar to the situation above, you can take advantage of callbacks.

How is this flexibility achieved? At first glance, callbacks seem to be just calls between functions, but if you think about it carefully, you can find a key difference between the two: in callbacks, we use a certain method to pass the callback function into the intermediate function like a parameter. It can be understood that the intermediate function is incomplete before a callback function is passed in. In other words, the program can decide and change the behavior of intermediate functions by registering different callback functions at runtime. This is much more flexible than simple function calls. Please look at the following simple example of a callback written in Python:

`even.py`
#回调函数1#生成一个2k形式的偶数def double(x):    return x * 2    #回调函数2#生成一个4k形式的偶数def quadruple(x):    return x * 4
`callback_demo.py`
from even import *#中间函数#接受一个生成偶数的函数作为参数#返回一个奇数def getOddNumber(k, getEvenNumber):    return 1 + getEvenNumber(k)    #起始函数,这里是程序的主函数def main():        k = 1    #当需要生成一个2k+1形式的奇数时    i = getOddNumber(k, double)    print(i)    #当需要一个4k+1形式的奇数时    i = getOddNumber(k, quadruple)    print(i)    #当需要一个8k+1形式的奇数时    i = getOddNumber(k, lambda x: x * 8)    print(i)    if __name__ == "__main__":    main()


Run `callback_demp.py`, the output is as follows:

3
5
9


In the above code, different callback functions are passed to `getOddNumber`, and their performances are also different. This is the advantage of the callback mechanism. It is worth mentioning that the third callback function above is an anonymous function.

Easy to be ignored third party

From the above discussion, it can be seen that the intermediate function and the callback function are two necessary parts of the callback, but people often ignore the third important role in the callback. , which is the caller of the intermediate function. In most cases, this caller can be equated with the main function of the program, but in order to express the difference, I call it the starting function here (as shown in the comments in the code above).

The reason why I specifically emphasize this third party is because I got the impression when I read relevant articles online that many people simply understand it as a call back and forth between two individuals. For example, when many Chinese web pages explain "callback", they will mention this sentence: "If you call me, I will call you back." I have not found the English source of this sentence. I personally speculate that many people regard the initial function and the callback function as one. There are probably two reasons: first, the name "callback" may be misleading; second, what kind of callback function is passed to the intermediate function? , is determined in the starting function. In fact, the callback is not the interaction between "you and me", but the three-party linkage of ABC. With this clear concept, it is less likely to cause confusion and errors when implementing callbacks in your own code.

In addition, there are actually two types of callbacks: blocking callbacks and delayed callbacks. The difference between the two is that in blocking callbacks, the callback function must occur before the initial function returns; while in delayed callbacks, the callback function may be called after the initial function returns. We are not going to discuss these two probabilities in more depth here. The reason why they are mentioned is to illustrate the importance of emphasizing the starting function. Many articles on the Internet, when mentioning these two concepts, just generally say that blocking callbacks occur before the main call function returns, but do not clarify whether the main call function is the starting function or the intermediate function, which inevitably makes people confused, so Here is a special explanation. Also note that the examples in this article are blocking callbacks. Delayed callbacks usually involve multi-threading. I haven't fully understood it yet, so I won't say more here.

Let me summarize here. Normally we write a function, which uses various API functions in the system, and then calls the function we wrote when needed; now the situation is reversed, we First write a function, which does not call the system API, and then we call the already written function through the system API, so that the function we write becomes the callback function.


The above is the detailed content of What is a callback function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn