Home >Backend Development >Python Tutorial >Detailed explanation of the meaning of callbacks in Python

Detailed explanation of the meaning of callbacks in Python

angryTom
angryTomforward
2019-11-30 13:18:465459browse

Detailed explanation of the meaning of callbacks in Python

Initial requirement background of callback function

The oldest scenario I can think of for callback function is the system programming meeting used.

Programming is divided into two categories:

● System programming

● Application programming

(Recommended learning: Python video tutorial )

What is system programming:

The so-called system programming, simply put, is to write various functions library. For example, the win32 and gdi32 libraries in Windows, win32 can call the functions of the host hardware and system layer, and gdi32 can be used to draw graphics. These libraries are just waiting for those who make applications to call them.

What is application programming:

Application programming is to use various system function libraries and language function libraries that have been written to write programs with certain business functions. A program is an application. For example, a basic crawler program can be completed using the Python language and the requests library, and a basic Web site can be completed using the Java language and the Java Servlet library.

The relationship between system programming and callbacks

System programmers will leave some interfaces, that is, APIs, 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 is running, under normal circumstances, the application 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. This function that is passed in and called later is called Callback function.

If you are confused by reading the text, then look at the picture I drew (below is Figure 1):

Detailed explanation of the meaning of callbacks in Python

Before understanding callbacks, first understand Synchronous call

Synchronous call is a blocking call. Simply put, it is executed from top to bottom in order. The callback is an asynchronous calling sequence.

The specific case of synchronous calling can be thought of the ancient beacon tower. The beacon transmission mechanism of the ancient Great Wall is similar to synchronous calling. Now we assume that each beacon can only see the status of adjacent beacons, and the status of each beacon is only bright (igniting state) and dark (not igniting state).

There are four beacon towers A, B, C, and D. A lights up first. B sees A's beacon light up and immediately goes to light it. It takes 2 seconds to light up. But the person in charge of C beacon was sleeping at this time, but at this time everyone was waiting for C to light up. Finally, C slept for 2 hours and saw B light up, and then went to light it up. D has not been lit for a long time, causing problems with the beacon, so the entire process is waiting for D to be completed. (This also led to some thinking. Synchronous calls are sometimes easy to lose the chain. If the chain is lost in the previous step, the operations after the next step will be finished.)

Case code of synchronous calls:

print("start.")
print(123)
print(456)
a = 7
if a > 6:
    print(789)
print(91011)
print("end.")

Problems that need to be solved with callbacks

Common systems will develop many libraries, and there are many functions in the libraries. Some functions require the caller to write the function to be called according to his own needs. Because this cannot be predicted when writing the library and can only be input by the caller, a callback mechanism is needed.

The callback mechanism is a way to improve the synchronous calling mechanism. The asynchronous calling mechanism is also used to improve the synchronous calling mechanism. (I will write an article later to introduce this more important asynchronous)

Case examples of how callback functions solve practical problems

Callbacks solve the above problems in the following ways.

● Functions can be turned into parameters

● Flexible and customized way to call

Function variable parameter case

def doubel(x):
    return 2*x
def quadruple(x):
    return 4*x
# mind function
def getAddNumber(k, getEventNumber):
    return 1 + getEventNumber(k)
def main():
    k=1
    i=getAddNumber(k,double)
    print(i)
    i=getAddNumber(k,quadruple)
    print(i)
# call main
main()

Output result:

3
5

Flexible and customized way to call (hotel wakes up passengers) case

This case is really the soul of callback. Suppose you are the front desk lady of the hotel, you cannot know the passengers who will check in tonight Do you need a wake-up call tomorrow? What kind of wake-up call is needed?

def call_you_phone(times):
    """
    叫醒方式: 给你打电话
    :param times: 打几次电话
    :return: None
    """
    print('已经给旅客拨打了电话的次数:', str(times))
def knock_you_door(times):
    """
    叫醒方式: 去敲你房间门
    :param times: 敲几次门
    :return: None
    """
    print('已经给旅客敲门的次数:', str(times))
def no_service(times):
    """
    叫醒方式: 无叫醒服务. (默认旅客是选无叫醒服务)
    :param times: 敲几次门
    :return: None
    """
    print('顾客选择无服务.不要打扰他的好梦。')
def front_desk(times, function_name=no_service()):
    """
    这个相当于酒店的前台,你去酒店之后,你要啥叫醒方式都得在前台说
    这里是实现回调函数的核心,相当于一个中转中心。
    :param times:次数
    :param function_name:回调函数名
    :return:调用的函数结果
    """
    return function_name(times)
if __name__ == '__main__':
    front_desk(100, call_you_phone)  # 意味着给你打100次电话,把你叫醒

Output:

已经给旅客拨打了电话的次数:100

Practical application (the event hook that comes with Python’s requests library)

This case is easy to solve. The original program is The synchronization mechanism is executed, but through hook events, some prior steps can be executed first. The principle of this hook event is function callback.

import requests
def env_hooks(response, *args, **kwargs):
    print(response.headers['Content-Type'])
def main():
    result = requests.get("https://api.github.com", hooks=dict(response=env_hooks))
    print(result.text)
if __name__ == '__main__':
    main()

Output:

application/json; charset=utf-8
{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"...省略"}

This article comes from the python tutorial column, welcome to learn!

The above is the detailed content of Detailed explanation of the meaning of callbacks in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete