1.装饰器的依赖--闭包:
Sample:
def Outer(a): start_time=time.time() def inner(b): print(a+b) end_time=time.time() print(end_time-start_time) return inner if __name__=="__main__": inn=Outer(1) inn(2)
2.最简单的装饰器:
Sample:
import time def decorator(func): def wrapper(): start_time=time.time() func() end_time=time.time() print(end_time-start_time) return wrapper @decorator def fun(): for i in range(1000000): pass print("This is the decorator .") if __name__=="__main__": fun()
3.目标函数带固定参数的装饰器
Sample:
import time def decorator(func): def wrapper(name): start_time=time.time() func(name) end_time=time.time() print(end_time-start_time) return wrapper @decorator def fun(user): for i in range(1000000): pass print("This is the %s."%user) if __name__=="__main__": fun("decorator")
4.目标函数带不固定参数的装饰器
Sample:
import time def decorator(func): def wrapper(*args,**kwags): start_time=time.time() func(*args,**kwags) end_time=time.time() print(end_time-start_time) return wrapper @decorator def fun(*args,**kwargs): for i in range(1000000): pass print("%s is the %s."%(args,kwargs)) if __name__=="__main__": fun("This",key="test")
5. 让装饰器带参数
Sample:import time def decorator(num): def _decorator(func): def wrapper(*args,**kwags): start_time=time.time() for i in range(num): func(*args,**kwags) end_time=time.time() print(end_time-start_time) return wrapper return _decorator @decorator(10) def fun(*args,**kwargs): for i in range(1000000): pass print("%s is the %s."%(args,kwargs)) if __name__=="__main__": fun("This",key="test")