装饰器

Posted baird

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。

 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")

 

以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章

Python面向对象学习之八,装饰器

thymeleaf 片段渲染后重新加载 javascript

代码缺乏装饰?使用ts装饰器来装饰你的代码

代码缺乏装饰?使用ts装饰器来装饰你的代码

代码缺乏装饰?使用ts装饰器来装饰你的代码

代码缺乏装饰?使用ts装饰器来装饰你的代码