码迷,mamicode.com
首页 > 编程语言 > 详细

python 入坑路--装饰器(语法糖)--高高潮

时间:2018-01-01 11:42:18      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:post   after   ati   com   col   index   pycha   rod   invalid   

上回我们说到,传入的函数带参数,这回我们要说的是,装饰器带参数,那么装饰器要如何是好。

 1 u_n="keven"
 2 passwd="abc123"
 3 
 4 def auth(auth_type):
 5     def outer_wrapper(func):
 6         def wrapper(*args,**kwargs):
 7             print(*args,**kwargs)
 8             username=input("pls input your username:").strip()
 9             passwrod=input("pls input your password:").strip()
10             if auth_type=="local":
11                 if username== u_n and passwrod==passwd:
12                     print("\033[5;40m user has pass authentication \033[0m") #给字体加颜色,装X
13                     res=func()
14                     print("after authentication") #w为了验证 函数执行后,能否将函数结果返回。
15                     return res
16                 else:
17                     print("Invalid passwrod or username")
18             elif auth_type == "ldap":
19                 print("先这样子,太复杂,老师没演示我也不懂")
20                 pass
21 
22         return wrapper  #确实记一定不能有括号,用pycharm 自动补全一直会带括号,坑。
23     return outer_wrapper
24 
25 
26 def index():
27     print("welcome to the index")
28 
29 @auth(auth_type="local") #装饰器带参数
30 def home():
31     print("welcome to the home")
32 
33 @auth(auth_type="ldap")#装饰器带参数
34 def bbs():
35     print("welcome to the bbs")
36 
37 
38 index()
39 home()
40 bbs()

 

python 入坑路--装饰器(语法糖)--高高潮

标签:post   after   ati   com   col   index   pycha   rod   invalid   

原文地址:https://www.cnblogs.com/chenkeven/p/8166100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!