python3:函数装饰器

发布时间 2023-04-27 00:46:43作者: lnlidawei

python3:函数装饰器

 

 

 

 

0、环境说明

1 wit@on:python3$ python3 -V
2 Python 3.10.6
3 wit@on:python3$ 
4 wit@on:python3$ 

 

 

 

 

一、代码

 1 wit@on:python3$ cat zhuangshiqi 
 2 #!/usr/bin/env python3
 3 
 4 
 5 
 6 
 7 # import part
 8 import time
 9 
10 
11 
12 
13 # codes part
14 
15 
16 def get_run_time(f):
17         def inner(*arg, **key):
18                 run_start = time.time()
19                 r = f(*arg, **key)
20                 run_end = time.time()
21                 run_time = run_end - run_start
22                 print(f"runtime := {run_time}")
23                 print(f"return_value := {r}\n")
24                 return r
25         return inner
26 
27 
28 @get_run_time
29 def fun1(x):
30         for i in range(x):
31                 j = i * 2
32         return j
33 
34 
35 def fun2(x):
36         for i in range(x):
37                 j = i * 2
38         return j
39 
40 
41 
42 # call fun1()/fun2()
43 # fun1(10) === get_run_time(fun2)(10)
44 fun1(10)
45 get_run_time(fun2)(10)
46 wit@on:python3$ 

 

 

 

 

二、运行结果

 1 wit@on:python3$ cat zhuangshiqi 
 2 #!/usr/bin/env python3
 3 
 4 
 5 
 6 
 7 # import part
 8 import time
 9 
10 
11 
12 
13 # codes part
14 
15 
16 def get_run_time(f):
17         def inner(*arg, **key):
18                 run_start = time.time()
19                 r = f(*arg, **key)
20                 run_end = time.time()
21                 run_time = run_end - run_start
22                 print(f"runtime := {run_time}")
23                 print(f"return_value := {r}\n")
24                 return r
25         return inner
26 
27 
28 @get_run_time
29 def fun1(x):
30         for i in range(x):
31                 j = i * 2
32         return j
33 
34 
35 def fun2(x):
36         for i in range(x):
37                 j = i * 2
38         return j
39 
40 
41 
42 # call fun1()/fun2()
43 # fun1(10) === get_run_time(fun2)(10)
44 fun1(10)
45 get_run_time(fun2)(10)
46 wit@on:python3$ 
47 wit@on:python3$ 
48 wit@on:python3$ ./zhuangshiqi 
49 runtime := 7.3909759521484375e-06
50 return_value := 18
51 
52 runtime := 5.4836273193359375e-06
53 return_value := 18
54 
55 wit@on:python3$ 
56 wit@on:python3$ 

 

 

 

 

三、参考资料:

  1、函数装饰器:  https://www.bilibili.com/video/BV1Ch4y1W7Kw