Python callback function Usage example detailed

Source: Internet
Author: User
This example describes the Python callback function usage. Share to everyone for your reference. The specific analysis is as follows:

First, the Baidu encyclopedia on the callback function explanation:

A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.

Second, what is a callback:

There is always a certain interface between software modules, which can be divided into three categories: synchronous invocation, callback and asynchronous invocation. A synchronous call is a blocking call that is returned when the caller waits for the execution to complete, a one-way invocation, or a two-way invocation pattern, that is, the callee invokes the interface when the interface is called, and the asynchronous invocation is a mechanism similar to a message or event, but it is called in the opposite direction. The service of an interface notifies the client (that is, the interface that invokes the client) when it receives a message or an event occurs. Callbacks are very closely related to asynchronous calls, and we typically use callbacks to register asynchronous messages and to implement notification of messages through asynchronous calls. Synchronous calls are the simplest of the three, and callbacks are often the basis of asynchronous invocations, so here we focus on the implementation of callback mechanisms in different software architectures.

A City small example:

#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_c All):   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 an object-oriented implementation found on the Web:

When you add a callback (Callback) function, the code tends to focus on the implementation of the callback rather than the problem itself. One solution is to implement a common base class to address the requirements of the callback, and then implement your method of binding (the binding) for an event.

The code is as follows:

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 R Eturn 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. Callba CK (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 ')

Here is a class that has two events (EVENT1 and EVENT2) and two processing functions (handler). The first handler function Handler1 registers the EVENT1, and the second handler Handler2 executes when EVENT1 or EVENT2 occurs (that is, all events are registered).

The running function (run) MyClass the corresponding event (dispatch) in its main loop. This (in this case, the dispatch function) returns a function that we can pass all the argument lists that need to be passed to the function. At the end of this function, a list is returned, and all the return values are in the list.

Perhaps the use of metaclass can be more elegant to achieve.

Hopefully this article will help you with Python programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.