Examples of Python callback function usage

Source: Internet
Author: User

Examples of Python callback function usage

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:

#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:

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.

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.