=====================================写法1========================== 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 def test1(): print(‘this is test1‘) def test2(): print(‘this is test2‘) test1 = timer(test1) 把deco内在地址赋值给test1 test1() #test1未被改变,而且调用方式也未被改变
=====================================写法2==========================
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 == test1 = timer(test1) @timer def test1(): print(‘this is test1‘) def test2(): print(‘this is test2‘) test1() #test1未被改变,而且调用方式也未被改变
=====================================修改写法2==========================
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 == test1 = timer(test1) @timer def test1(): time.sleep(3) print(‘this is test1‘) def test2(name,age): time.sleep(3) print(‘this is test2‘) print(‘name:%s,age:%s‘ %(name,age)) test1() #test1未被改变,而且调用方式也未被改变 test2(‘大盗林工‘,18)
以上三个例子若被装饰的函数有返回值,则返回值为空,即以上三个例子的返回值都被修改了,若要使返回值不被修改,请查python中装饰器的应用
时间: 2024-10-20 11:50:34