首页 > 技术文章 > 装饰器

dachenzi 2017-03-25 13:45 原文

 
装饰器:
  定义:本质是函数,功能是用来装饰其他函数(就是为其他函数添加附加功能)。
  原则:1、不能修改被装饰的函数的源代码
       2、不能修改被装饰的函数的调用方式
装饰器对于被装饰的函数是透明的(既函数本身不知道自己被装饰)
 
 
实现装饰器知识储备:
  1、函数即“变量”
  2、高阶函数
    a.把一个函数名当作参数传递给另外一个函数
    b.返回值中包含函数名
  3、函数嵌套
 
小结:利用高阶函数+嵌套函数完成装饰器的功能
 
例子:
 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:

 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')

 

推荐阅读