- #!/usr/bin/env python
- #created by Baird
- import time
- def timer(deco_type): #三层装饰器, 第一层接收额外参数
- if deco_type == "type1":
- def type_select(func): #第二层接收被装饰函数名
- def deco(*args, **kargs): #第三层接收被装饰函数参数
- start_time = time.time()
- ret = func(*args, **kargs) #接收被装饰函数返回值
- end_time = time.time()
- print("This is decoration 1. Executive time is", start_time - end_time)
- return ret #返回原被装饰函数返回值
- return deco
- return type_select
- def type_select2(func):
- def deco(*args, **kargs):
- start_time = time.time()
- ret = func(*args, **kargs)
- end_time = time.time()
- print("This is decoration 2. Executive time is", start_time - end_time)
- return ret
- return deco
- return type_select2
- @timer(deco_type = "type1") #func = timer(func) = type_select(func)
- def func():
- print("Start func")
- time.sleep(2)
- print("Exit func")
- return("Function1")
- @timer(deco_type = "type2") #func2 = timer(func2) = type_select2(func2)
- def func2(name):
- print("name is",name)
- return("Functon2")
- print(func())
- print(func2("Baird"))
- print()
- def timer2(func): #二层装饰器, 第一层接收被装饰函数
- def deco(*args,**kargs): #第二层接收被装饰函数参数
- start_time = time.time()
- ret = func(*args,**kargs) #接收被装饰函数返回值
- end_time = time.time()
- print("Executive time is",end_time-start_time)
- return ret #返回原被装饰函数返回值
- return deco
- @timer2 #func3 = timer2(func3)
- def func3():
- print("This is func3")
- return("Function3")
- @timer2 #func4 = timer2(func4)
- def func4(say):
- print("This is func4",say)
- return("Function4")
- func3()
- func4("hello")
装饰器
来源: http://www.bubuko.com/infodetail-2744312.html