装饰器(decorator):
1>定义: 本质是函数,功能是用来装饰其他函数,为其他函数添加附加功能
2>原则:(1)不能修改被装饰函数的源代码;(2);不能修改呗装饰的函数的调用方式
实现装饰器知识储备:(1)函数即变量(2)高阶函数(满足其一就是:一个函数作为另一个函数的入参;返回值包含函数名(3)嵌套函数
高阶函数 + 嵌套函数 = 修饰器
1.简单的装饰器,统计接口运行时间
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import timedef timer(func): def deco(*args,**kwargs): start_time = time.time() return func(*args,**kwargs) end_time = time.time() print('the run time is %s'%(end_time-start_time)) return deco# test1 = timer(test1)@timerdef test1(times): time.sleep(times) print('in the test1') return timesprint(test1(1)) |
输出结果:
|
1
2
|
in the test11 |
2.模拟某些函数需要登陆验证,验证方式分为本地和ldap验证(完整版)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#模拟某些函数需要登陆验证,验证方式分为本地和ldap验证userName,passWord ="Bert","abc123" #假设是数据库用户名密码def auth(auth_type): def outer_wrapper(func): def wrapper(*args,**kwargs): if auth_type == 'local': user_name =input('Username:').strip() pass_word =input('Password:').strip() if user_name == userName and pass_word == passWord: print("用户名密码验证成功!") return func(*args,**kwargs) else: print("用户名密码验证失败!") elif auth_type == 'ldap': print('ldap方式验证登录。。。') return func(*args,**kwargs) return wrapper return outer_wrapperdef index(): print('in the index') return 'index'@auth(auth_type="local") #auth_type装饰器最外层函数的入参def home(): print('in the home') return 'home'@auth(auth_type="ldap")def bbs(): print('in the bbs') return 'bbs'index()home()bbs() |