Python函数(九)-装饰器(二)
如果给被装饰器装饰的函数传递参数的话,需要在装饰器里修改
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import time def timer(func): def deco(n): #需要在此处设置形参 start_time = time.time() func(n) stop_time = time.time() print("the run time is %s"%(stop_time-start_time)) return deco @timer def test1(name): time.sleep(3) print('My name is %s'%name) test1('John')
运行结果
但是有两个或者多个被装饰的函数需要传递参数的话,这种情况就不太方便了
所以可以直接用*args和**kwargs,不管被装饰的函数有几个,传递的参数有多少,不管是什么类型的参数
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import time def timer(func): def deco(*args,**kwargs): #需要在此处设置形参 start_time = time.time() func(*args,**kwargs) stop_time = time.time() print("the run time is %s"%(stop_time-start_time)) return deco @timer def test1(name,age): time.sleep(3) print('My name is %s and my age is %s'%(name,age)) @timer def test2(name,language,city): time.sleep(1) print('%s is studying %s in %s'%(name,language,city)) test1('John',22) test2('Jack',city='beijing',language='Chinese')
运行结果