python 回调函数

def apply_async(func, args,  callback):
# Compute the result
   result = func(*args)
# Invoke the callback with the result
   callback(result)
def print_result(result):
   print('Got:', result)

def add(x, y):
   return x + y
apply_async(add, (2, 3), callback=print_result)

C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a22.py
('Got:', 5)

# !/usr/bin/env python
# -*- coding: utf-8 -*-
def apply_async(func, args,  callback):
# Compute the result
   result = func(*args)
# Invoke the callback with the result
   callback(result)
def print_result(result):
   print('Got:', result)

def add(x, y):
   return x + y
apply_async(add, (2, 3), callback=print_result)
class ResultHandler:
   def __init__(self):
      self.sequence = 0
   def handler(self, result):
      self.sequence += 1
      print ('[{}] Got: {}'.format(self.sequence, result))

##实例化对象
r = ResultHandler()
##r.handler 调用对象方法
apply_async(add, (2, 3), r.handler)

C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a22.py
('Got:', 5)
[1] Got: 5


原文地址:https://www.cnblogs.com/hzcya1995/p/13349438.html