search
HomeBackend DevelopmentPython TutorialDetailed explanation of the meaning of callbacks in Python

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:博客园. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool