笔记5: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")
def event(*args, **kwargs):
time.sleep(*args, **kwargs)
print('i am a event what you need now!')
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
""" 装饰符的使用 """
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')