1 # File : learning_012_decorators.py.py
2 # Datetime : 2022/4/14 0014 3:27
3
4 import time
5
6
7 # 装饰器
8 # 本质上,装饰器是一个函数,用来处理其他函数,
9 # 可以让其他函数在不需要修改代码的前提下增加额外的功能,装饰器返回的对象也是一个函数.
10
11 # 常用的装饰器需求场景有:插入日志、性能检测、事务处理、缓存、权限校验等
12
13 # 代码演练装饰器场景示例: 代码性能检测,可以选择性的插入日志
14 def insert_log(flag=False):
15 def show_time(function_name):
16 def wrapper():
17 start_date = time.time()
18 function_name()
19 time.sleep(1) # 设置程序停留时长
20 end_date = time.time()
21 if flag:
22 print("日志插入成功!")
23 print("程序执行时间为", end_date - start_date)
24
25 return wrapper
26
27 return show_time
28
29
30 # @show_time # 相当于my_function=show_time(my_function)
31 @insert_log(True) # 相当于insert_log=show_time(my_function)
32 def my_function():
33 print("我的测试代码")
34
35
36 my_function()
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/244427.html