1.装饰器

定义:本质是函数,功能:(装饰其他函数)就是为其他函数添加附件功能。
原则:1.不能修改被装饰的函数的源代码。
   2.不能修改被装饰的函数的调用方式。
实现装饰器的知识储备:
  1.函数即"变量"
  2.高阶函数
    a:把一个函数名当作实参传给另外一个函数。(在不修改被装饰函数源代码的情况下为其添加功能)
    b:返回值中包含函数名。(不修改函数的调用方式)
  3.嵌套函数
高阶函数+嵌套函数 => 装饰器
@timmer #装饰器或语法糖

示例代码:

 1 # -*- coding:utf-8 -*-
 2 # Author: JACK ZHAO
 3 
 4 username = "test"
 5 password = "test123"
 6 
 7 def auth(auth_type):
 8     def out_wrapper(func):
 9         def wrapper(*args, **kwargs):
10             if auth_type == "local":
11                 _username = input("Username:").strip()
12                 _password = input("Password:").strip()
13                 if username == _username and _password == password:
14                     print("\033[32;1mUser has passed authentication\033[0m")
15                     res = func(*args, **kwargs)
16                     return res
17                 else:
18                     print("\033[31;1mInvalid username or password.\033[0m")
19                     exit()
20             elif auth_type == "ldap":
21                 print("\033[32;1mUser has passed sshkey\033[0m")
22                 res = func(*args, **kwargs)
23                 return res
24         return wrapper
25     return out_wrapper
26 
27 def  index():
28     print("welcome to index page.")
29     return ("From index")
30 @auth(auth_type="local")  #重点:home = auth(auth_type="local")(home)
31 def home():
32     print("welcome to home page.")
33     return ("From home")
34 
35 @auth(auth_type="ldap")
36 def bbs():
37     print("welcome to bbs page.")
38     return ("From bbs")
39 
40 index()
41 home()
42 bbs()

 

划重点:(不太好理解的)
@auth #不带参数的装饰器,等价于 home = auth(home)
@auth(auth_type="local") #带参数的装饰器,等价于 home = auth(auth_type="local")(local),先执行auth(auth_type="local"),获取out_wrapper函数的内存地址,再将home的内存地址当做实参传给wrapper
def home():
  pass

 
 

posted on 2017-11-19 11:37  ChangMingZhao  阅读(112)  评论(0)    收藏  举报

导航