Python callback function usage example
This example describes the usage of the Python callback function. Share it with you for your reference. The specific analysis is as follows:
I. Baidu encyclopedia's explanation of callback functions:
A callback function is a function called by a function pointer. If you pass the pointer (address) of a function as a parameter to another function, when this pointer is used to call the function to which it points, we will say this is a callback function. The callback function is called by another party when a specific event or condition occurs instead of by the implementer of the function. It is used to respond to the event or condition.
Ii. What is callback:
There are always some interfaces between software modules. In terms of calling methods, they can be divided into three types: Synchronous call, callback and asynchronous call. Synchronous call is a blocking call. The caller must wait for the execution of the other party to complete before returning. It is a one-way call. Callback is a two-way call mode, that is, the called party also calls the other party's interface when the interface is called. asynchronous call is a mechanism similar to messages or events, but its call direction is the opposite, when an interface service receives a message or an event, it proactively notifies the customer (that is, the customer's interface ). Callback and asynchronous call are closely related. Generally, callback is used to register asynchronous messages and message notifications are implemented through asynchronous calls. Synchronous calling is the simplest of the three, and callback is often the basis of asynchronous calling. Therefore, we will focus on the implementation of callback mechanisms in different software architectures.
3. A small example:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Call. py Import called Def callback (): Print "in callback" Def main (): # Called. test () Called. test_call (callback) Print "in call. py" Main () # Called. py ''''' Def test (): Print "in called. py test ()" ''' Def test_call (p_call ): Print "in called. py test_call ()" P_call () Joe @ joe :~ /Test/python $ python call. py In called. py test_call () In callback In call. py Joe @ joe :~ /Test/python $ |
An example of object-oriented implementation found on the Internet:
When you want to add the Callback function, the Code tends to focus on Callback implementation rather than the problem. One solution is to implement a general basic class to solve the callback requirement, and then implement the Method you bind to an Event ).
The Code is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
Class CallbackBase: Def _ init _ (self ): Self. _ callbackMap = {} For k in (getattr (self, x) for x in dir (self )): If hasattr (k, "bind_to_event "): Self. _ callbackMap. setdefault (k. bind_to_event, []). append (k) Elif hasattr (k, "bind_to_event_list "): For j in k. bind_to_event_list: Self. _ callbackMap. setdefault (j, []). append (k) # Staticmethod is only used to create a namespace @ Staticmethod Def callback (event ): Def f (g, ev = event ): G. bind_to_event = ev Return g Return f @ Staticmethod Def callbacklist (eventlist ): Def f (g, evl = eventlist ): G. bind_to_event_list = evl Return g Return f Def dispatch (self, event ): L = self. _ callbackMap [event] F = lambda * args, ** kargs :\ Map (lambda x: x (* args, ** kargs), l) Return f # Sample Class MyClass (CallbackBase ): EVENT1 = 1 EVENT2 = 2 @ CallbackBase. callback (EVENT1) Def handler1 (self, param = None ): Print "handler1 with param: % s" % str (param) Return None @ CallbackBase. callbacklist ([EVENT1, EVENT2]) Def handler2 (self, param = None ): Print "handler2 with param: % s" % str (param) Return None Def run (self, event, param = None ): Self. dispatch (event) (param) If _ name _ = "_ main __": A = MyClass () A. run (MyClass. EVENT1, 'mandarina ') A. run (MyClass. EVENT2, 'naranja ') |
There is a class, which has two events (EVENT1 and EVENT2) and two handler functions (handler ). The first handler, handler1, registers EVENT1, and the second handler, handler2, is executed when EVENT1 or EVENT2 occurs (that is, all events are registered ).
Run is in the main loop of MyClass, And it will dispatch the corresponding event (dispatch. This (here refers to the dispatch function) will return a function. We can pass the list of all parameters that need to be passed to this function to it. After the function is run, a list is returned, which contains all returned values.
Maybe Metaclass is more elegant.
I hope this article will help you with Python programming.