程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Thoroughly understand the callback function in Python

編輯:Python

Catalog

Abstract

What is a callback function

Advantages of callback mechanism

Asynchronous processing of related callback functions

Use a binding method instead of this simple function .

  Use closures instead of the above classes to implement

Use a coroutine to complete an asynchronous operation

summary

Abstract

It's mainly about python Callback function for callback.

What is a callback function

When the program is running , In general , Applications often pass through API Call the pre prepared function in the library . But some library functions require the application to pass it a function first , Good to call at the right time , To achieve the goal . This was introduced into 、 The function that is called later is called the callback function (callback function).

for example :

There is a hotel that provides wake-up service , However, passengers are required to decide how to wake up . It could be a room call , You can also send a waiter to knock on the door , I'm so sleepy that I'm afraid of delaying things , You can also ask to pour a basin of water on your head . here ,“ Wake up ” This behavior is provided by the hotel , Equivalent to library function , But the way to wake up is decided by the passengers and told the hotel , That's the callback function . And passengers tell the hotel how to wake themselves up , That is, the action of transferring the callback function to the storage function , be called Register callback function (to register a callback function)

You can see , Callback functions are usually at the same level of abstraction as applications ( Because what kind of callback function is passed in is determined at the application level ). The callback becomes a high-level call and the low-level call , The bottom layer goes back and calls the high-level process .( In my submission ) This should be the earliest application of callback , That's why it's so named .

Advantages of callback mechanism

Callback mechanism provides great flexibility . We change the library function in the figure to Intermediate function 了 , This is because callbacks are not just used between applications and Libraries . anytime , As long as you want flexibility similar to the above situation , You can use callbacks . Some students can decide Callbacks seem to be just calls between functions , You can see a key difference between the two

In the callback , We use some way , Pass the callback function into the intermediate function like a parameter . It's understandable , Before passing in a callback function , The intermediate function is incomplete . let me put it another way , The program can run , By registering different callback functions , To decide 、 Change the behavior of the intermediate function . This is much more flexible than simple function calls .

# Callback function 1# Generate a 2k Even number of forms def double(x): return x * 2# Callback function 2# Generate a 4k Even number of forms def quadruple(x): return x * 4callback_demo.py`from even import *# Intermediate function # Take a function that generates an even number as an argument # Returns an odd number def getOddNumber(k, getEvenNumber): return 1 + getEvenNumber(k)# Starting function , Here is the main function of the program def main(): k = 1 # When you need to generate a 2k+1 When the form is odd i = getOddNumber(k, double) print(i) # When you need a 4k+1 When the form is odd i = getOddNumber(k, quadruple) print(i) # When you need a 8k+1 When the form is odd i = getOddNumber(k, lambda x: x * 8) print(i)if __name__ == "__main__": main() Asynchronous processing of related callback functions def apply_ascyn(func, args, callback): """ func Function is the function of processing args Parameters represented by callback After the function processing is completed Action to perform """ result = func(*args) callback(result)def add(x, y): return x + ydef print_result(result): print(result)apply_ascyn(add, (2, 3), callback=print_result)

here print_result Only one... Can be received result Parameters of , No other information can be passed in . When you want the callback function to access the values of other variables or variables in a specific environment, you will encounter problems .

Use a binding method instead of this simple function .def appy_async(func, args, *, callback): result = func(*args) # Functions executed asynchronously At the same time, it will return to this function after execution and jump out of this function callback(result)def add(x ,y): return x + yclass ResultHandler(object): def __init__(self): self.sequence = 0 def handle(self, result): self.sequence += 1 print("[{}] Got: {}".format(self.sequence, result))resultHandler = ResultHandler()appy_async(add, (2,3), callback=resultHandler.handle)

  Use closures instead of the above classes to implement def apply_async(func, args, *, callback): result = func(*args) callback(result)def add(x ,y): return x + ydef make_handler(): sequence = 0 def handler(result): nonlocal sequence sequence += 1 print("[{}] Got:{}".format(sequence, result)) return handlerhandler = make_handler()apply_async(add, (2,3), callback=handler) Use a coroutine to complete an asynchronous operation def apply_async(func, args, *, callback): result = func(*args) callback(result)def add(x, y): return x + ydef make_handler(): sequence = 0 while True: result = yield sequence += 1 print("[{}] Got:{}".format(sequence, result))handle = make_handler()next(handle)apply_async(add, (2,3), callback=handle.send)

Blog reference :

python3 Callback function (callback) - You know

summary

This is about Python Middle callback function (callback) This is the end of the article , More about Python Callback function callback Please search the previous articles of software development network or continue to browse the relevant articles below. I hope you will support software development network more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved