首页 > 代码库 > python学习:装饰器用法

python学习:装饰器用法

 1 #!/usr/bin/env python
 2 #coding:utf-8
 3 
 4 name="alex"
 5 psw="abc123"
 6 
 7 def  auth(func):
 8      def wrapper(*args,**kwargs):
 9          username=input(input your username:)
10          password=input(input your password:)
11 
12          if username==name and  password==psw :
13             return func(*args,**kwargs)
14          else:
15              print(Inalid username and password!)
16      return wrapper
17 
18 
19 @auth
20 def home():
21     print(home)
22     return home!!
23 @auth
24 def admin():
25     print(admin)
26 @auth
27 def bbs():
28     print(bbs)
29 
30 home()
31 admin()
32 bbs()

增加多种类型验证

 1 #!/usr/bin/env python
 2 #coding:utf-8
 3 
 4 name="alex"
 5 psw="abc123"
 6 
 7 def  auth(auth_type):
 8      print(---------,auth_type)
 9      def out_wrapper(func):
10          print(---------,func)
11          def wrapper(*args,**kwargs):
12              username=input(input your username:)
13              password=input(input your password:)
14 
15              if username==name and  password==psw :
16                 return func(*args,**kwargs)
17              else:
18                  print(Inalid username and password!)
19          return wrapper
20      return out_wrapper
21 
22 #增加login多种验证
23 @auth(auth_type=file)
24 def home():
25     print(home)
26 @auth(auth_type=localhost)
27 def admin():
28     print(admin)
29 @auth(auth_type=ldap)
30 def bbs():
31     print(bbs)
32 
33 home()
34 admin()
35 bbs()

 

python学习:装饰器用法