装饰器和高阶函数

装饰器和高阶函数

装饰器:本质就是函数
功能:为其他函数添加附加功能
原则:不修改被修饰函数的源代码
       不修改被调用函数的调用方式
装饰器 = 高阶函数 + 函数嵌套 + 闭包
#高阶函数:
#函数的返回是一个函数名
#函数接受的参数是一个函数名
#满足上述其中一种为高阶函数

 1 import time
 2 def foo():
 3     time.sleep(3)
 4     print('来自foo')
 5 def timer(func):
 6     start_time = time.time()
 7     func()
 8     stop_time = time.time()
 9     print('函数运行的时间为%s'%(stop_time-start_time))
10     return func
11 foo = timer(foo)
12 foo()

运行结果:

来自foo
函数运行的时间为3.0148422718048096
(隔三秒):
来自foo

Process finished with exit code 0

装饰器的实现:

 1 import time
 2 def summ(func):#装饰器
 3     time.sleep(3)
 4     print('summ函数运行结束')
 5     def wap():
 6         start_time = time.time()
 7         func()
 8         stop_time = time.time()
 9         print('时间差为%s'%(stop_time-start_time))
10     return wap
11 @summ # @summ 相当于 test = summ(test) @语法糖
12 def test():
13     time.sleep(2)
14     print('test函数运行结束')
15 # res = summ(test)
16 #res()
17 # test = summ(test)
18 test()
(隔三秒):
summ函数运行结束
test函数运行结束
时间差为2.01023530960083

Process finished with exit code 0

装饰器实现加返回值:

 1 import time
 2 def summ(func):#func = test
 3     print('这是summ函数')
 4     def wap():
 5         print('wap函数')
 6         start_time = time.time()
 7         res = func()#运行test()
 8         stop_time = time.time()
 9         print('test()函数运行时间为%s'%(stop_time-start_time))
10         return res#运行的是test()函数 所以返回值为test()的return值
11     return wap
12 @summ #test = summ(test)
13 def test():
14     time.sleep(3)
15     print('test函数执行完毕')
16     return '这是test的返回值'
17 # test()
18 res = test()#运行wap() 所以返回值为wap()的返回值
19 print(res)#wap()的返回值

运行结果:

这是summ函数
wap函数
test函数执行完毕
test()函数运行时间为3.0004074573516846
这是test的返回值

Process finished with exit code 0

装饰器被(@)修饰加参数:

 1 import time
 2 def summ(func):#func = test
 3     print('这是summ函数')
 4     def wap(*args,**kwargs):
 5         print('wap函数')
 6         start_time = time.time()
 7         res = func(*args,**kwargs)#运行test()
 8         stop_time = time.time()
 9         print('test()函数运行时间为%s'%(stop_time-start_time))
10         return res#运行的是test()函数 所以返回值为test()的return值
11     return wap
12 @summ #test = summ(test)
13 def test(name,age):
14     time.sleep(3)
15     print('test函数执行完毕,姓名是%s,年龄是%d'%(name,age))
16     return '这是test的返回值'
17 res = test('alex',18)#运行wap() 所以返回值为wap()的返回值
18 print(res)#wap()的返回值
19 
20 
21 def test1(name,age,sex):
22     time.sleep(1)
23     print('test函数执行完毕,姓名是%s,年龄是%d,性别是%s'%(name,age,sex))
24     return '这是test的返回值'
25 res1 = test1('alex',18,'male')#运行wap() 所以返回值为wap()的返回值
26 print(res1)#wap()的返回值

运行结果:

这是summ函数
wap函数
test函数执行完毕,姓名是alex,年龄是18
test()函数运行时间为3.013343095779419
这是test的返回值
test函数执行完毕,姓名是alex,年龄是18,性别是male
这是test的返回值

Process finished with exit code 0

验证功能装饰器:

 1 user_list = [
 2     {'name':'alex','passwd':'123'},
 3     {'name':'g_l','passwd':'123456'},
 4     {'name':'aiji','passwd':'123'},
 5     {'name':'wuji','passwd':'123'}
 6 ]#用户信息
 7 current_dic = {'username':None,'login':False}#当前用户状态
 8 def auth_func(func):
 9     def swap(*args,**kwargs):
10         if current_dic['username'] and current_dic['login']:
11             res = func(*args, **kwargs)
12             return res
13         username = input('用户名:').strip()
14         passwd = input('密码:').strip()
15         for user_dic in user_list:
16             if username == user_dic['name'] and passwd == user_dic['passwd']:
17                 current_dic['username']=username
18                 current_dic['login']=True
19                 res = func(*args, **kwargs)
20                 return res
21         else:
22             print('用户名或者密码错误')
23             # if username == 'g_l'and passwd == '123':
24             #     user_dic['username']=username
25             #     user_dic['login']=True
26             #     res = func(*args,**kwargs)
27             #     return res
28             # else:
29             #     print('用户名或者密码错误')
30     return swap
31 @auth_func
32 def home(name):
33     print('欢迎回家%s'%name)
34 @auth_func
35 def shopping_car(name):
36     print('%s购物车里有:%s,%s,%s'%(name,'CPU','内存条','固态硬盘'))
37 @auth_func
38 def index():
39     print('欢迎来到京东')
40 
41 print('before--->',current_dic)
42 index()
43 print('after--->',current_dic)
44 home('g_l')
45 shopping_car('g_l')

运行结果:

before---> {'username': None, 'login': False}
用户名:g_l
密码:123456
欢迎来到京东
after---> {'username': 'g_l', 'login': True}
欢迎回家g_l
g_l购物车里有:CPU,内存条,固态硬盘

Process finished with exit code 0

验证功能装饰器加参数:

 1 user_list = [
 2     {'name':'alex','passwd':'123'},
 3     {'name':'g_l','passwd':'123456'},
 4     {'name':'aiji','passwd':'123'},
 5     {'name':'wuji','passwd':'123'}
 6 ]#用户信息
 7 current_dic = {'username':None,'login':False}#当前用户状态
 8 def auth(auth_type ):
 9     def auth_func(func):
10         def swap(*args,**kwargs):
11             print('认证类型是:',auth_type)
12             if auth_type == 'filedb':
13                 if current_dic['username'] and current_dic['login']:
14                     res = func(*args, **kwargs)
15                     return res
16                 username = input('用户名:').strip()
17                 passwd = input('密码:').strip()
18                 for user_dic in user_list:
19                     if username == user_dic['name'] and passwd == user_dic['passwd']:
20                         current_dic['username']=username
21                         current_dic['login']=True
22                         res = func(*args, **kwargs)
23                         return res
24                 else:
25                     print('用户名或者密码错误')
26             elif auth_type=='ldap':
27                 print('ldap认证类型 ,但是不会玩')
28                 res = func(*args, **kwargs)
29                 return res
30             else:
31                 print('不知道这是什么认证类型')
32                 res = func(*args, **kwargs)
33                 return res
34         return swap
35     return auth_func
36 @auth(auth_type='glgl')
37 def index():
38     print('欢迎来到京东')
39 @auth(auth_type='filedb')#运行auth函数 将auth_func = auth_type='filedb'传给下层函数  相当于@auth_func(添加了一个auth_type的形参)
40 def home(name):
41     print('欢迎回家%s'%name)
42 
43 @auth(auth_type='ldap')
44 def shopping_car(name):
45     print('%s购物车里有:%s,%s,%s'%(name,'CPU','内存条','固态硬盘'))
46 
47 
48 # print('before--->',current_dic)
49 
50 index()
51 # print('after--->',current_dic)
52 home('g_l')
53 shopping_car('g_l')

运行结果:

 

认证类型是: glgl
不知道这是什么认证类型
欢迎来到京东
认证类型是: filedb
用户名:g_l
密码:123456
欢迎回家g_l
认证类型是: ldap
ldap认证类型 ,但是不会玩
g_l购物车里有:CPU,内存条,固态硬盘

Process finished with exit code 0

posted @ 2018-06-09 21:32 容颜-gl 阅读(...) 评论(...) 编辑 收藏

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值