• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
66zhyh99
博客园    首页    新随笔    联系   管理    订阅  订阅

笔记5:python回调函数

python回调函数:

同步

 
 
 
 
 
 
 
def click(func,*args,**kwargs):
    func()
    print 'callback over'
​
def callback():
    time.sleep(1)
    print 'i am callback'
​
click(callback)
 
 
 
 
 
 
 
 
i am callback
callback over
 

异步

 
 
 
 
 
 
 
import threading
import time


def callback(func):
    def wrapper(*args, **kwargs):
        t = threading.Thread(target=func, args=args,kwargs=kwargs)
        t.start()

    return wrapper


def click(func, *args, **kwargs):
    func(*args, **kwargs)
    print("callback maybe not end,but i need tell him that i've received his command")


@callback
def event(*args, **kwargs):
    time.sleep(*args, **kwargs)
    print('i am a event what you need now!')


@callback
def another_event(*args, **kwargs):
    time.sleep(*args, **kwargs)
    print('i am another event you need now!')


click(event,3)
click(another_event,6)
 

返回

其中,先学习@的最一般用法:

就是建立一个新的函数,来取代你想用的函数,其中新的函数前后包含你想要作的事.

 
 
 
 
 
 
 
from datetime import datetime
​
def record_time(func):
    """ 建立一个新的函数 """
    def new_function(*args, **kwargs):
        now = datetime.now()
        print(f'func called at {now}')
        value = func(*args, **kwargs)
        print(f'Execution time is {datetime.now()-now}')
        return value
    """ 返回这个新的函数 """
    return new_function
​
""" 装饰符的使用 """
@record_time
def circle_area(radius):
    area = 3.14*radius**2
    print(f'Area of circle with radius {radius} is {area}')
    return area
​
circle_area(3)
 

该装饰符就放在函数定义前一行,其意义等同于把 circle_area 函数更改为我们在 record_time 中所定义的新函数.

 
 
 
 
 
 
 
callback maybe not end,but i need tell him that i've received his command
callback maybe not end,but i need tell him that i've received his command
1213
>>> i am another event you need now!
i am a event what you need now!

>>> 
 

我们看回去:

 
 
 
 
 
 
 
import time
from multiprocessing import Process,Pool
​
# call1,call2,call3分别为3个主函数
def call1(n):
    time.sleep(n)
    print("call:", 1)
    return 1
​
def call2(n):
    time.sleep(n)
    print("call:", 2)
    return 2
​
def call3(n):
    time.sleep(n)
    print("call:", 3)
    return 3
​
def fun(n):
    # 回调函数,表示执行完主函数后要完成的工作
    print("i'm done!, n={}".format(n))
​
​
if __name__ == "__main__":
    print('start')
    
    p = Pool(3)   # 建立进程池
    # 分别用异步的方式执行主函数call,主函数参数n,以及回调函数fun
    p.apply_async(func=call1, args=(1, ), callback=fun)
    p.apply_async(func=call2, args=(1, ), callback=fun)
    p.apply_async(func=call3, args=(1, ), callback=fun)
    p.close()
    p.join()
    
    print('end')
    
​

 

 
posted @ 2022-03-11 19:39  66zhyh99  阅读(127)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3