裝飾器

 
裝飾器:
  定義:本質是函數,功能是用來裝飾其餘函數(就是爲其餘函數添加附加功能)。
  原則:一、不能修改被裝飾的函數的源代碼
       二、不能修改被裝飾的函數的調用方式
裝飾器對於被裝飾的函數是透明的(既函數自己不知道本身被裝飾)
 
 
實現裝飾器知識儲備:
  一、函數即「變量」
  二、高階函數
    a.把一個函數名看成參數傳遞給另一個函數
    b.返回值中包含函數名
  三、函數嵌套
 
小結:利用高階函數+嵌套函數完成裝飾器的功能
 
例子:
 1 user = 'daxin'
 2 passwd = '123456'
 3 
 4 def auth_type(auth_type):
 5     def auth(func):
 6         def auth_page(*args):
 7             if auth_type == 'local':
 8                 username = input('Please input your user:')
 9                 password = input("Please input your passwd:")
10                 if username == user and passwd == password:
11                     func(*args)
12                 else:
13                     print('Username or password Error!')
14             else:
15                 print('LDAP')
16                 func(*args)
17         return auth_page
18     return auth
19 
20 def index():
21     print('in the index page')
22 @auth_type('local')      --> local傳遞到最外層的func
23 def home():
24     print("in the home page")
25 @auth_type('ldap')
26 def bbs():
27     print('in the bbs page')
28 
29 index()
30 home()
31 bbs()

 

 

例子2:app

 1 import functools
 2 
 3 def decorator(logintype='3'):
 4     def decorator1(func):
 5         @functools.wraps(func)
 6         def wrapper(*args,**kwargs):
 7             if logintype == '1':
 8                 print('begin call')
 9                 func(*args,**kwargs)
10                 print('end call')
11             elif logintype == '2':
12                 print('start call')
13                 func(*args,**kwargs)
14                 print('over call')
15             else:
16                 print('test start')
17                 func(*args,**kwargs)
18                 print('test start')
19         return wrapper
20     return decorator1
21 
22 
23 @decorator()
24 def a(name):
25     print('in the F name is %s' % name)
26 
27 @decorator('2')
28 def b():
29     print('in the B')
30 @decorator('1')
31 def c():
32     print("in the C")
33 
34 c()
35 b()
36 a('123')
相關文章
相關標籤/搜索