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
原文:https://www.cnblogs.com/azxsdcv/p/14265750.html