python_装饰器

Posted on 2018-08-02 21:30  Pyner  阅读(78)  评论(0)    收藏  举报

装饰器(语法糖)

定义: 本质是行数,(装饰其他函数)就是为了其他函数添加附加功能!

 

原则: 1.不能就该被装饰的函数的源代码。

    2.不能修改被装饰的函数的调用方式。

 

实现装饰器的知识储备:

  1.函数即“变量”。(在Python中一切皆为对象)

  2.高阶函数:a 把一个函数名当作实参传给另外一个函数。

          b 返回值中包含函数名

  3.嵌套函数

    def func():

      def func1():  #局部变量(函数即变量)

        pass

      pass

 

高阶函数+嵌套函数 ==> 装饰器

 

通用的装饰器:(装饰器带参数,装饰的函数带参数)

 

 1 import time
 2 
 3 def auth(auth_type):
 4     print('auth func:', auth_type)
 5 
 6     def out_wrapper(func):
 7         def wrapper(*args, **kwargs):   #通用被装饰函数传参
 8             print('wrapper func args:', *args, **kwargs)
 9             if auth_type == 'local':
10                 print('\033[32;1mUser has passed authentication\033[0m')
11                 res = func(*args, **kwargs) #通用被装饰函数返回值
12                 print('--after authenticaion')
13                 return res
14 
15             elif auth_type == 'ldap':
16                 print('哈哈,我不会ldap')
17                 res = func(*args, **kwargs) #通用被装饰函数返回值
18                 print('--after authenticaion')
19                 return res
20         return wrapper
21     return out_wrapper
22         
23 
24 @auth(auth_type = 'local')  #先执行auth(arges),再用out_wrapper(home)装饰
25 def home():
26     print('welcome to home  page')
27     return 'from home'
28 
29 @auth(auth_type = 'ldap')
30 def bbs():
31     print('welcome to bbs page')
32     return 'from bbs'
33 
34 
35 home()
36 bbs()