What is a callback, the callback meaning in programming

Initially demand background callback function

The callback function I can think of is the scene of the oldest programming system will be used.

Programming is divided into two categories:

  • Programming system (system programming)
  • Application Programming (application programming)

What is System Programming:
The so-called system programming, simply put, it is written in a variety of libraries. For example, Windows inside win32, gdi32 library, win32 can call the host hardware and system function layer, gdi32 can be used to draw graphics-related. These libraries are waiting for those who do apply to call on the line.

What is the application programming:
The application programming is the use of various system functions already written libraries, language function library to write programs with certain business functions used, is the application. For example, a crawler-based program, you can use the language and requests python library to complete a basic Web site can use the Java language and the Java Servlet library to complete.

Relations system programming and callback

System programmers to write their own libraries will leave some interface, that API, for use by programmers. So illustration abstraction layer, the library is located under applications. When the program run, in general, the application will always call the library as a prepared in advance by the function API. 但是有些库函数却要求应用先传给它一个函数,好在合适的时候调用,以完成目标任务。This is passed, then the function is called is called the callback function (callback function).

If you see the text see more ignorant, then you see I painted Figure (Figure 1 below):

Before the callback understand, to understand the synchronization call

A blocking call is a synchronous invocation, in short, from the top down, the order of execution. The callback is a non-synchronous call-type sequence.

For example: the flames of the ancient Great Wall of transmission of information, we now assume that each war only to see flames neighboring state, the status of each of the flames only light and dark.

There are A, B, C, D four flames, first lit A, B A, see the bright flames, immediately to the ignition, the lighting took 2 seconds. But this time the person in charge of C war in sleep, but this time everyone is waiting for the lights C, C finally slept two child saw the B light, and then go light up. D is not lit due to the long, leading to problems with the flames, so the whole process is waiting for the completion of D.

Case synchronous call code:

print("start.")
print(123)
print(456)

a = 7
if a > 6:
    print(789)

print(91011)
print("end.")

Callback problem to be solved

Common system will be developed many libraries, there are many library functions. And some function, the caller need to write a function to call according to their needs. Because this can not predict at the time of writing the library, it can only be entered by the caller, so you need a callback mechanism.


Case callback how to solve practical problems

Callback is said to solve the above problem as follows.

  • Function parameters can become
  • Flexible, customizable 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:

3
5


Flexible, customizable way to call (Wake up hotel guests) Case

This case is really the soul of the callback, assuming you are a small sister hotel's front desk, you can not know tonight travelers staying or need to do tomorrow, wake-up service, what kind of wake-up service needs.

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 (Python library that comes with the requests of the event hook)

This case was originally on the program is a good solution to perform synchronization mechanism, but by hook event, you can give priority to perform some steps ahead. And this principle is to hook event callback function.

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":"...省略"}


After-school Questions

After reading the above case, please answer the following questions

1. callbacks used in those scenes?
2. The callback function as a parameter must do?
3. Where the difference and asynchronous callbacks in?

Put your thoughts in the comments inside comments section, I will find time to give you a reply.


references

Reference: https://www.zhihu.com/question/19801131
Reference: https://blog.csdn.net/dan15188387481/article/details/50016227

Guess you like

Origin www.cnblogs.com/mysticbinary/p/11869181.html