Callback and event-driven
The callback function has a more important meaning: it is an event-driven embodiment
Let's think of a scenario where if we trigger an event, such as a click event
So just give the click event one or more processing events, that is, the callback function
We can call the appropriate method to handle the funeral after the Click event is triggered (after the end)
Like what
Normal callback
#在函数中使用回调def Click (callback): eval (callback) () #eval () can tell the string to parse into executable code DEF handle: print ' calls the function after the end of the Click event. processing, such as popup alert () ' if (__name__ = = ' __main__ '): fun1 (' fun2 ')
The above scene is obviously a simulation of our daily use of the browser is a scene:
When we click on a button, a warning box or confirmation box may pop up, which can be interpreted as
After clicking on the event trigger, call this handler function, the function is to pop up a warning box or confirmation box
From event-driven: Click the event's send driver to trigger this handle handler
Well, will this be clearer?
Use callbacks in class
Because Python is an object-oriented location from the start, as a Python programmer, you might face the following scenario:
We create an instance, we pass in the data to this instance, and finally we get the results we want, like we passed to
An object named Getcsdntitle a URL (a URL to a CSDN blog), we want to finally get the text content of this article,
Do we first get the HTML content of the URL by HTTP request, name the method Fetch_url ()
Then we need to deal with the HTML, such as filtering, regular matching, string processing, we want to get the text content, to this method named
Get_content ()
In this case, we need to go through the Fetch_url and get_content two ways to get the final result we need, and the two are obviously
The sequential difference we can understand as called after Fetch_url callback Get_content method, you might say that this is not a lot of trouble,
In fact, we have to know that the actual development of this execution chain is likely to be very long, through the callback, we can specify after a certain step after the execution of what we want to do
Operation, which will be efficient both logically and in understanding.
Here's a small example of how to implement callbacks in a class
#在类中使用回调方法
#在函数中使用回调def Click (callback): eval (callback) () #eval () can tell the string to parse into executable code DEF handle: print ' calls the function after the end of the Click event. processing, such as popup alert () ' if (__name__ = = ' __main__ '): fun1 (' fun2 ')