python知识点—— 装饰器

装饰器的定义:

装饰器本身就是函数(高级函数+嵌套函数)

装饰器的好处:

在不修改已有函数内容以及调用方式的基础上,为已有函数增加新的功能逻辑

举例说明:

在web项目中 四个功能模块在进入时,需要身份验证,通过装饰器,可以在不修改四个功能模块的情况下,为四个方法根据需求(参数)来做相应的验证功能

理解:

装饰器,在spring中就是AOP 面向切面编程,也就是常说的注解,无论名字怎么称呼,最终的中心思想就是,一种编码的设计模式,目的是便于 程序的开发以及后期维护,装饰器思想在很多语言中有体现,方式和叫法略有不同,核心思想殊途同归

例子代码:

 1 # __author__ = '19134'
 2 import sys
 3 import time
 4 
 5 
 6 #装饰器
 7 def a_type(arg_type):
 8     if arg_type == 'a':
 9         def ornament_test(func):
10             def f(*args, **kwargs):
11                 start_time = time.time()
12                 res = func(*args, **kwargs)
13                 end_time = time.time()
14                 print('is ornament_test')
15                 return res
16             return f
17         return ornament_test
18     else:
19         def ornament_test(func):
20             def f(*args, **kwargs):
21                 res = func(*args, **kwargs)
22                 print('nothing')
23                 return res
24             return f
25         return ornament_test
26 
27 
28 
29 @a_type(arg_type='b')
30 def test():
31     #time.sleep(2)
32     return 'in the test'
33 
34 
35 @a_type(arg_type='b')
36 def test2(name):
37     print(name)
38 
39 
40 print(test())
41 test2('senxu')

 

posted @ 2019-10-25 15:16  田园先生  阅读(105)  评论(0)    收藏  举报