day20-python之装饰器

2023-01-31 00:01:52 day20

1.装饰器

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 def cal(l):
 5     start_time=time.time()
 6     res=0
 7     for i in l:
 8         time.sleep(0.1)
 9         res+=i
10     stop_time = time.time()
11     print('函数的运行时间是%s' %(stop_time-start_time))
12     return res
13  
14 
15 
16 print(cal(range(100)))
17 
18 
19 def index():
20     pass
21 
22 def home():
23     pass

2.装饰器预演

 1 #!/usr/bin/env Python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 def timmer(func):
 5     def wrapper(*args,**kwargs):
 6         start_time=time.time()
 7         res=func(*args,**kwargs)
 8         stop_time = time.time()
 9         print('函数运行时间是%s' %(stop_time-start_time))
10         return res
11     return wrapper
12  
13 def timmer1(func):
14     def wrapper(*args,**kwargs):
15         start_time = time.time()
16         res = func(*args,**kwargs)
17         stop_time = time.time()
18         print('函数运行时间是%s' %(stop_time-start_time))
19         return res
20     return wrapper()
21 
22 
23 @timmer
24 def cal(l):
25     res=0
26     for i in l:
27         time.sleep(0.1)
28         res+=i
29     return res
30 
31 res=cal(range(20))
32 print(res)
33 
34 
35 def index():
36     pass
37 
38 def home():
39     pass

3.高阶函数

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 '''
 4 高阶函数定义:
 5 1.函数接收的参数是一个函数名
 6 2.函数的返回值是一个函数名
 7 3.满足上述条件任意一个,都可称之为高阶函数
 8 '''
 9 # import time
10 # def foo():
11 #     time.sleep(3)
12 #     print('你好啊林师傅')
13 
14 # def test(func):
15 #     # print(func)
16 #     start_time=time.time()
17 #     func()
18 #     stop_time = time.time()
19 #     print('函数运行时间是  %s' % (stop_time-start_time))
20 # foo()
21 # test(foo)
22 
23 # def foo():
24 #     print('from the foo')
25 # def test(func):
26 #     return func
27 # res=test(foo)
28 # # print(res)
29 # res()
30 
31 
32 import time
33 def foo():
34     time.sleep(3)
35     print('来自foo')
36 
37 #不修改foo源代码
38 #不修改foo调用方式
39 
40 #多运行了一次,不合格
41 # def timer(func):
42 #     start_time=time.time()
43 #     func()
44 #     stop_time = time.time()
45 #     print('函数运行时间是  %s' % (stop_time-start_time))
46 #     return func
47 # foo=timer(foo)
48 # foo()
49 
50 
51 #没有修改被修饰函数的源代码,也没有修改被修饰函数的调用方式,但是也没有为被修饰函数添加新功能
52 # def timer(func):
53 #     start_time=time.time()
54 #     return func
55 #     stop_time = time.time()
56 #     print('函数运行时间是  %s' % (stop_time-start_time))
57 #
58 # foo=timer(foo)
59 # foo()
60  

4.函数嵌套

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # def bar():
 4 #     print('from bar')
 5 #
 6 # def foo():
 7 #     print('from foo')
 8 #     def test():
 9 #         pass
10 
11 def father(auth_type):
12     # print('from father %s' %name)
13     def son():
14         # name='linhaifeng_1'
15         # print('我的爸爸是%s' %name)
16         def grandson():
17             print('我的爷爷是%s' %auth_type)
18         grandson()
19     # print(locals())
20     son()
21 # father('linhaifeng')
22 father('filedb')

5.加上返回值

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 def timmer(func): #func=test
 5     def wrapper():
 6         start_time=time.time()
 7         res=func() #就是在运行test()
 8         stop_time = time.time()
 9         print('运行时间是%s' %(stop_time-start_time))
10         return res
11     return wrapper
12 
13 @timmer #test=timmer(test)
14 def test():
15     time.sleep(3)
16     print('test函数运行完毕')
17     return '这是test的返回值'
18 
19 # res=test()  #就是在运行wrapper
20 # print(res)

 6.加上参数

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 def timmer(func): #func=test1
 5     def wrapper(*args,**kwargs): #test('linhaifeng',age=18)  args=('linhaifeng')  kwargs={'age':18}
 6         start_time=time.time()
 7         res=func(*args,**kwargs) #就是在运行test()         func(*('linhaifeng'),**{'age':18})
 8         stop_time = time.time()
 9         print('运行时间是%s' %(stop_time-start_time))
10         return res
11     return wrapper
12 
13 
14 
15 # @timmer #test=timmer(test)
16 
17 def test(name,age):
18     time.sleep(3)
19     print('test函数运行完毕,名字是【%s】 年龄是【%s】' %(name,age))
20     return '这是test的返回值'
21 
22 @timmer
23 def test1(name,age,gender):
24     time.sleep(1)
25     print('test1函数运行完毕,名字是【%s】 年龄是【%s】 性别【%s】' %(name,age,gender))
26     return '这是test的返回值'
27 
28 res=test('linhaifeng',age=18)  #就是在运行wrapper
29 print(res)
30 # test1('alex',18,'male')
31 
32 # test1('alex',18,'male')
33 
34 
35 
36 
37 
38 # def test2(name,age,gender): #test2(*('alex',18,'male','x','y'),**{})
39 #     #name,age,gender=('alex',18,'male','x','y')
40 #     print(name)
41 #     print(age)
42 #     print(gender)
43 #
44 # def test1(*args,**kwargs):
45 #     test2(*args,**kwargs)  #args=('alex',18,'male','x','y') kwargs={}
46 #
47 # # test2('alex',18,gender='male')
48 #
49 # test1('alex',18,'male')

7.装饰器实现

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import time
 4 def timmer(func): #func=test
 5     def wrapper():
 6         # print(func)
 7         start_time=time.time()
 8         func() #就是在运行test()
 9         stop_time = time.time()
10         print('运行时间是%s' %(stop_time-start_time))
11     return wrapper
12 
13 @timmer #test=timmer(test)
14 def test():
15     time.sleep(3)
16     print('test函数运行完毕')
17 test()
18 
19 # res=timmer(test)  #返回的是wrapper的地址
20 # res()  #执行的是wrapper()
21 
22 # test=timmer(test)  #返回的是wrapper的地址
23 # test()  #执行的是wrapper()
24 
25 #  @timmer  就相当于 test=timmer(test)

8.验证功能装饰器

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 user_list=[
 4     {'name':'alex','passwd':'123'},
 5     {'name':'linhaifeng','passwd':'123'},
 6     {'name':'wupeiqi','passwd':'123'},
 7     {'name':'yuanhao','passwd':'123'},
 8 ]
 9 current_dic={'username':None,'login':False}
10 
11 
12 def auth_func(func):
13     def wrapper(*args,**kwargs):
14         if current_dic['username'] and current_dic['login']:
15             res = func(*args, **kwargs)
16             return res
17         username=input('用户名:').strip()
18         passwd=input('密码:').strip()
19         for user_dic in user_list:
20             if username == user_dic['name'] and passwd == user_dic['passwd']:
21                 current_dic['username']=username
22                 current_dic['login']=True
23                 res = func(*args, **kwargs)
24                 return res
25         else:
26             print('用户名或者密码错误')
27 
28     return wrapper
29 
30 @auth_func
31 def index():
32     print('欢迎来到京东主页')
33 
34 @auth_func
35 def home(name):
36     print('欢迎回家%s' %name)
37 
38 @auth_func
39 def shopping_car(name):
40     print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))
41 
42 print('before-->',current_dic)
43 index()
44 print('after--->',current_dic)
45 home('产品经理')
46 shopping_car('产品经理')

10.带参数验证功能装饰器

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 user_list=[
 4     {'name':'alex','passwd':'123'},
 5     {'name':'linhaifeng','passwd':'123'},
 6     {'name':'wupeiqi','passwd':'123'},
 7     {'name':'yuanhao','passwd':'123'},
 8 ]
 9 current_dic={'username':None,'login':False}
10 
11 def auth(auth_type='filedb'):
12     def auth_func(func):
13         def wrapper(*args,**kwargs):
14             print('认证类型是',auth_type)
15             if auth_type == 'filedb':
16                 if current_dic['username'] and current_dic['login']:
17                     res = func(*args, **kwargs)
18                     return res
19                 username=input('用户名:').strip()
20                 passwd=input('密码:').strip()
21                 for user_dic in user_list:
22                     if username == user_dic['name'] and passwd == user_dic['passwd']:
23                         current_dic['username']=username
24                         current_dic['login']=True
25                         res = func(*args, **kwargs)
26                         return res
27                 else:
28                     print('用户名或者密码错误')
29             elif auth_type == 'ldap':
30                 print('鬼才特么会玩')
31                 res = func(*args, **kwargs)
32                 return res
33             else:
34                 print('鬼才知道你用的什么认证方式')
35                 res = func(*args, **kwargs)
36                 return res
37 
38         return wrapper
39     return auth_func
40 
41 @auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')-->@auth_func 附加了一个auth_type  --->index=auth_func(index)
42 def index():
43     print('欢迎来到京东主页')
44 
45 @auth(auth_type='ldap')
46 def home(name):
47     print('欢迎回家%s' %name)
48 #
49 @auth(auth_type='sssssss')
50 def shopping_car(name):
51     print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))
52 
53 # print('before-->',current_dic)
54 # index()
55 print('after--->',current_dic)
56 home('产品经理')
57 # shopping_car('产品经理')

 

相关文章