标签:cti 修改 调用 time() time span strong else sleep
装饰器的作用:扩展函数功能。
特点:1.不修改原函数代码
2.保持调用函数不变
原理:高阶函数 + 嵌套函数 = 装饰器
1 # Author = Johnston 2 import time 3 def timer(func): 4 def deco(): 5 start_time = time.time() 6 func() 7 end_time = time.time() 8 print("the function run time is %s" %(end_time-start_time)) 9 return deco 10 11 @timer #bar = timer(bar),@time必须写在需装饰的函数前面 12 def bar(): 13 time.sleep(3) 14 print("in the bar") 15 16 bar()
无参数装饰器
# Author = Johnston import time def timer(func): def deco(name): #传递参数name start_time = time.time() func(name) end_time = time.time() print("the function run time is %s" %(end_time-start_time)) return deco @timer #bar = timer(bar),@timer必须写在需装饰的函数前面 def bar(name): time.sleep(3) print("%s is in the bar" %name) bar("Johnston")
内参装饰器
1 # Author = Johnston 2 import time 3 def outpara(type): 4 def timer(func): 5 def deco(name): 6 if type==1: #根据外参数作为判断执行条件 7 start_time = time.time() 8 func(name) 9 end_time = time.time() 10 print("the function run time is %s" %(end_time-start_time)) 11 else: 12 print("wrong type") 13 return deco 14 return timer 15 16 @outpara(type=1) #传递条件参数,@outpara必须写在需装饰的函数前面
17 def bar(name):
18 time.sleep(3)
19 print("%s is in the bar" %name)
20
21 bar("Johnston")
外参装饰器
标签:cti 修改 调用 time() time span strong else sleep
原文地址:http://www.cnblogs.com/automate/p/7624928.html