1. 程式人生 > 其它 >筆記5:python回撥函式

筆記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')