码迷,mamicode.com
首页 > 其他好文 > 详细

装饰器

时间:2018-08-27 14:01:35      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:exe   sleep   select   star   his   imp   col   usr   rgs   

 1 #!/usr/bin/env python
 2 #created by Baird
 3 
 4 import time
 5 
 6 def timer(deco_type):       #三层装饰器,第一层接收额外参数
 7     if deco_type == "type1":
 8         def type_select(func):         #第二层接收被装饰函数名
 9             def deco(*args, **kargs):       #第三层接收被装饰函数参数
10                 start_time = time.time()
11                 ret = func(*args, **kargs)      #接收被装饰函数返回值
12                 end_time = time.time()
13                 print("This is decoration 1. Executive time is ", start_time - end_time)
14                 return ret          #返回原被装饰函数返回值
15             return deco
16         return type_select
17 
18     def type_select2(func):
19         def deco(*args, **kargs):
20             start_time = time.time()
21             ret = func(*args, **kargs)
22             end_time = time.time()
23             print("This is decoration 2. Executive time is ", start_time - end_time)
24             return ret
25         return deco
26 
27     return type_select2
28 
29 @timer(deco_type = "type1")      #func = timer(func) = type_select(func)
30 def func():
31     print("Start func")
32     time.sleep(2)
33     print("Exit func")
34     return("Function1")
35 
36 @timer(deco_type = "type2")     #func2 = timer(func2) = type_select2(func2)
37 def func2(name):
38     print("name is ",name)
39     return("Functon2")
40 
41 print(func())
42 print(func2("Baird"))
43 
44 print()
45 
46 def timer2(func):       #二层装饰器,第一层接收被装饰函数
47     def deco(*args,**kargs):        #第二层接收被装饰函数参数
48         start_time = time.time()
49         ret = func(*args,**kargs)       #接收被装饰函数返回值
50         end_time = time.time()
51         print("Executive time is ",end_time-start_time)
52         return ret      #返回原被装饰函数返回值
53     return deco
54 
55 @timer2         #func3 = timer2(func3)
56 def func3():
57     print("This is func3")
58     return("Function3")
59 
60 @timer2         #func4 = timer2(func4)
61 def func4(say):
62     print("This is func4 ",say)
63     return("Function4")
64 
65 func3()
66 func4("hello")

 

装饰器

标签:exe   sleep   select   star   his   imp   col   usr   rgs   

原文地址:https://www.cnblogs.com/baird/p/9541370.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!