20210112-1 裝飾器之案例剖析2
阿新 • • 發佈:2021-01-12
1-1 # 如果 test2 裡面有一個引數 import time def timer(func): def deco(): start_time = time.time() func() stop_time = time.time() print("the func run time is %s" %(stop_time-start_time)) return deco @timer def test1(): time.sleep(3) print('in the test1') @timer def test2(name): print("test2:",name) test1() test2() ---> TypeError: test2() missing 1 required positional argument: 'name' # 結果是出錯的,test2 缺少位置引數 name # @timer 相當於 test2 = timer(test2) # test2 傳到裡面都做了什麼? test2 → func → 執行 deco 所以,內嵌的deco函式,執行了嗎? # return deco,直接返回了 deco 的記憶體地址 # test2 其實是等於 deco,於是 test2()相當於 deco(),執行到 func()時,相當於執行到了 test2() # 但是 test2 是要求傳引數的,test2()沒有傳參;所以會報錯 # 那麼,這種情況應該如何處理?如何把引數傳進來?
1-2 # test2(name),其實就是相當於 deco(name) import time def timer(func): def deco(arg1): start_time = time.time() func(arg1) stop_time = time.time() print("the func run time is %s" %(stop_time-start_time)) return deco @timer def test2(name):print("test2:",name) test2("alex") ---> test2: alex the func run time is 0.0
1-2-1 # 如果傳入兩個引數呢? # 要裝飾的函式可能是各種各樣的功能 # 所以需要 *args **kwargs import time def timer(func): def deco(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print("the func run time is %s" %(stop_time-start_time)) return deco @timer def test1(): time.sleep(3) print('in the test1') @timer def test2(name,age): print("test2:",name,age) test1() test2("alex",11) ---> in the test1 the func run time is 3.0008721351623535 test2: alex 11 the func run time is 0.0009975433349609375