(Xviii) python 3 callback function

The callback function : the pointer (address) function is passed as a parameter to another function, when the pointer is used to call the function it points to, we say this is a callback function. Callback function is not called directly by the parties to achieve the function, but by another calling party when a particular event or condition occurs, for response to the event or condition.

Popular is understood that : as an argument to a function to another function, the first function is called a callback function. This is the argument passed is actually a function pointer, that is a pointer to a function of (address).

 

There is always a certain amount of interfaces between software modules, from the invocation, we can put them into three categories: synchronous calls, callback and asynchronous calls.

  • Synchronous call is a blocking call, the caller to wait for the other side is finished before returning, it is a one-way call;
  • Callback is a two-way call mode, that is, the caller will call the other side of the interface when the interface is called;
  • Asynchronous call is a message mechanism or similar event, but it's just the opposite direction of calls, service interface upon receipt of certain messages or certain events occur, will take the initiative to inform the client side (ie call interface on the client side.

Callback and asynchronous invocation relationship is very close, we usually use to implement asynchronous callback message registration notification message is implemented by asynchronous call. Synchronous calls are among the easiest of the three, but they often are the basis callback asynchronous call, so let's focus on the realization of a callback mechanism in different software architecture

Case number one
import random as rd

# Callee ----------- ----------------------------
def newRN (fn): # 10 generates a decimal between [0,1)
    ns = []
    for i in range(10):
        n = round(rd.random(), 2)
        ns.append(n)

    # No direct return, because the caller will not receive notification return result
    # Way into the callback function
    fn (ns) # call is the caller function, this operation is called a callback

# Caller ------------------------ ----------------

# Define the callback function
def abc(*args):
    # Enter into this function, meaning that called function has completed execution
    print ( 'generates data success')
    print(args)

newRN(abc)

  

Case II

import  random as rd
import time

def test(fn, n):
        """
        Test n random number generation time required (in seconds)
        : Param fn: callback function
        : Param n: number of generation
        :return:
        """
        start_time = time.time () # Start Time

        for i in range(n):
            rd.random()
            time.sleep (0.1) # 0.1 seconds to allow the CPU to sleep

            the time.time end_time = time () end of the cycle #
            seconds = round (end_time - start_time) # execution time
            Number fn (seconds, n) # postback with (seconds), n generated


def test_callback(tm_s,n):
    print ( '{0} generated number, when {1} with s' .format (n, tm_s))


test(test_callback, 20)

  

Case III

def findNumbers(path, num, fn):
    l = []
    Equally = 1
    with open(path, 'r+') as f:
        for line in f.readlines():
            index = line.find(str(num))
            if index != -1:
                l.append((rowNo, index + 1))
            Equally + = 1
    fn(l)


def callback_(sl):
    print(sl)


findNumbers('222.txt', 5, callback_)

  

Guess you like

Origin www.cnblogs.com/a-ant/p/11013346.html