iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >day20-python之装饰器
  • 931
分享到

day20-python之装饰器

python 2023-01-31 00:01:52 931人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

1.装饰器 1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import time 4 def cal(l): 5 start_time=time.time()

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('产品经理')

 

--结束END--

本文标题: day20-python之装饰器

本文链接: https://www.lsjlt.com/news/182282.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • day20-python之装饰器
    1.装饰器 1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import time 4 def cal(l): 5 start_time=time.time() ...
    99+
    2023-01-31
    python
  • Python之装饰器
    在Python中一切皆对象,函数是一等对象。这意味着可以通过名字引用函数。>>> a=123 >>> a 123 >>> name='zeng' >>> name 'z...
    99+
    2023-01-31
    Python
  • Python 语法之装饰器
      装饰器的概念  装饰器是 Python 的一个重要部分。简单地说:就是用于拓展原来函数功能的一种函数,目的是在不改变原函数名(或类名)的情况下,给函数增加新的功能。  这个函数的特殊之处在于它的返回值也是一个函数,这个函数是内嵌 “原”...
    99+
    2023-06-02
  • python之yield与装饰器
    防伪码:忘情公子著python中的yield:  在之前发布的《python之列表解析与生成器》中我们有提到过,生成器所实现的是跟列表解析近似的效果,但是我们不能对生成器做一些属于列表解析的操作。  因为生成器本身就不是一个列表,它只是模拟...
    99+
    2023-01-31
    python yield
  • python进阶之装饰器
    一.无参装饰器 问题:如何计算一段程序的运行时间? 先看一段简单代码: 1 import time 2 def func(): 3 start = time.time() # 记录程序开始时间 4 time.sleep(...
    99+
    2023-01-30
    进阶 python
  • python之装饰器(函数)
    1. 装饰器   遵循的原则:     开闭原则:   对功能的扩展开放  对代码的修改是封闭 # 通用装饰器写法 # 存在的意义: 在不破坏原有函数和原有函数调用的基础上,给函数添加新的功能. def wrapper...
    99+
    2023-01-30
    函数 python
  • Python 3 之 装饰器详解
    ------------ 装饰器 -----------------------------------------------------什么是装饰器装饰器是为函数和类指定管理代码的一种方式。装饰器本身的形式是处理其他的可调用对象的可调用...
    99+
    2023-01-31
    详解 Python
  • Python学习之装饰器与类的装饰器详解
    目录装饰器装饰器的定义装饰器的用法类中的装饰器类的装饰器 - classmethod类的装饰器 - staticmethod类的装饰器 - property通过学习装饰器可以让我们更...
    99+
    2024-04-02
  • python学习系列之python装饰器
    一、常规的装饰器,比如 @auth,执行2步操作:1、执行auth函数,并传参func进来2、获取返回值,并赋值给被装饰器的函数的函数名(如让fetch_server_list等于返回值)二、而带参数的装饰器,比如 @auth(before...
    99+
    2023-01-31
    系列之 python
  • Python全栈开发之---装饰器
    1、装饰器的形成过程 1 import time 2 3 def func1(): 4 print('in func1') 5 6 def timer(func): 7 def inner(): 8...
    99+
    2023-01-30
    Python
  • python魔术方法之装饰器
    三个魔术方法:__get__()__set__()__delete__()object.__get__(self,实例名,owner)    #owner = 属主 ,instance = 属主类owner的实例object.__set__...
    99+
    2023-01-31
    魔术 方法 python
  • python装饰器2:类装饰器
    装饰器1:函数装饰器 装饰器2:类装饰器 装饰器3:进阶 本文是装饰器相关内容的第二篇,关于类装饰器。 "类装饰器"有两种解读方式:用来装饰类的装饰器;类作为装饰器装饰其它东西。你如何认为取决于你,两种说法都有出现在其它的文章中。我的...
    99+
    2023-01-30
    python
  • python基础之装饰器详解
    目录一、前言二、高阶函数三、函数嵌套四、装饰器4.1 被装饰方法带返回值4.2 被装饰方法带参数4.3 验证功能装饰器4.4 验证功能装饰器——带参数一、前言 装...
    99+
    2024-04-02
  • python三大器之装饰器详解
    目录装饰器总结装饰器 讲装饰器之前要先了解两个概念: 对象引用 :对象名仅仅只是个绑定内存地址的变量 def func(): # 函数名仅仅只是个绑定内存地址的...
    99+
    2024-04-02
  • Python语法详解之decorator装饰器
    python 是一门优雅的语言,有些使用方法就像魔法一样。装饰器(decorator)就是一种化腐朽性为神奇的技巧。最近一直都在使用 Tornado 框架,一直还是念念不忘 Flas...
    99+
    2024-04-02
  • python之我对装饰器的理解
      从一开始学习python的时候,就一直不是很理解装饰器是个什么东东,再看了很多篇博文和自己动手敲了好多代码后,算是略有了解。  我理解的装饰器是: 在不改变原有函数调用的情况下,对其进行包装,使其变成另外一种函数来使用,一般的用途是 插...
    99+
    2023-01-31
    我对 python
  • python装饰器
    什么是装饰器:   装饰器就是python中的一个语法糖。作用就是在不改动之前代码的情况下给某个函数增加相应想要增加的功能。 假设需求:   我在几个函数内分别放了一部电影,代码如下: 1 def mv1(): 2 print(...
    99+
    2023-01-30
    python
  • python-装饰器
    装饰器简介:给被装饰的函数在不更改代码的基础上增加新的功能;多个装饰器的执行顺序:从最靠近原始函数的装饰器开始执行,最后执行原始函数; 直接上个简单的例子就懂了: 一 最简单的装饰器:#!/usr/bin/python def deco(f...
    99+
    2023-01-31
    python
  • Python函数式编程之装饰器
    原则:对修改是封闭的,对扩展是开放的,方法:一般不修改函数或者类,而是扩展函数或者类一:装饰器 允许我们将一个提供核心功能的对象和其他可以改变这个功能的对象’包裹‘在一起, 使用装饰对象的任何对象与装饰前后该对象的交互遵循完全...
    99+
    2023-01-30
    函数 Python
  • python总结之闭包和装饰器
    目录一、装饰器1.装饰器的简单介绍2.装饰器的解析过程二、闭包三、闭包中nonlocal语句的使用1.外部变量的引用和改写2.nolocal的使用及特点四、闭包与装饰器五、闭包的作用...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作