python文件下载速度 装饰器_python学习笔记之---装饰器

# -*- coding:utf-8 -*-

'''示例1: 最简单的函数,表示调用了两次'''

def myfunc():

print ("myfunc() called.")

myfunc()

myfunc()

E:\>py -3 a.py

myfunc() called.

myfunc() called.

第二步:使用装饰函数在函数执行前和执行后分别附加额外功能

'''示例2: 替换函数(装饰)装饰函数的参数是被装饰的函数对象,返回原函数对象

装饰的实质语句: myfunc = deco(myfunc)'''

defdeco(func):print ("before myfunc() called.")

func()print ("after myfunc() called.")returnfuncdefmyfunc():print ("myfunc() called.")

myfunc=deco(myfunc)

myfunc()

myfunc()

E:\>py -3 a.py

before myfunc() called.

myfunc() called.

after myfunc() called.

myfunc() called.

myfunc() called.

第三步:

'''示例3: 使用语法@来装饰函数,相当于“myfunc = deco(myfunc)”

但发现新函数只在第一次被调用,且原函数多调用了一次'''

defdeco(func):print ("before myfunc() called.")

func()print ("after myfunc() called.")returnfunc

@deco #等价于:deco(myfunc)defmyfunc():print ("myfunc() called.")

myfunc()

myfunc()

E:\>py -3 a.py

before myfunc() called.

myfunc() called.

after myfunc() called.

myfunc() called.

myfunc() called.

------->>>>>>

执行逻辑:

deco(myfunc)

print ("before myfunc() called.")

myfunc()

print ("  after myfunc() called.")

print (" myfunc() called.")

print (" myfunc() called.")

第四步:使用内嵌包装函数来确保每次新函数都被调用

装饰器的规则:

规则1:

函数func上面定义了@xxxx,那么等价于 func = xxxx(func)

规则2:

装饰函数xxxx,必须返回一个闭包(一个内置函数+func)

'''示例4: 使用内嵌包装函数来确保每次新函数都被调用,

内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装

函数对象'''

defdeco(func):def_deco():print ("before myfunc() called.")

func()print ("after myfunc() called.")#不需要返回func,实际上应返回原函数的返回值

return_deco

@decodefmyfunc():print ("myfunc() called.")return 'ok'myfunc() #---->执行闭包函数_deco()

myfunc()#---->执行闭包函数_deco()

#myfunc=deco(myfunc)----->返回一个闭包:_deco的函数+myfunc

E:\>py -3 a.py

before myfunc() called.

myfunc() called.

after myfunc() called.

before myfunc() called.

myfunc() called.

after myfunc() called.

分析:

defdeco(func):def_deco():print ("before myfunc() called.")

func()print ("after myfunc() called.")#不需要返回func,实际上应返回原函数的返回值

return_deco

闭包:_deco+func

@decodefmyfunc():print ("myfunc() called.")return 'ok'myfunc=deco(myfunc)

myfunc是什么?是闭包:_deco+myfunc

myfunc()--->_deco()

myfunc()--->_deco()defouter(name):definner():print(name)returninner

闭包:inner+name

执行过程解释:

装饰函数deco

被装饰函数myfunc

@deco

def myfunc():   --->myfunc= deco(myfunc)

myfunc= deco(myfunc)干了什么呢?

1 调用了deco(myfunc)

2  返回闭包:_deco+外包变量myfunc

3 闭包赋值给了myfunc

4 提醒myfunc变为了闭包函数对象

myfunc()---》干了什么呢?

1 _deco()执行了

2 print ("before myfunc() called.")

3 myfunc()

4 print ("  after myfunc() called.")

myfunc()---》干了什么呢?

1 _deco()执行了

2 print ("before myfunc() called.")

3 myfunc()

4 print ("  after myfunc() called.")

第五步:对带参数的函数进行装饰

'''示例5: 对带参数的函数进行装饰,

内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装

函数对象'''

defdeco(func):def_deco(a, b):print ("before myfunc() called.")

ret=func(a, b)print ("after myfunc() called. result: %s" %ret)returnretreturn_deco

@decodefmyfunc(a, b):print ("myfunc(%s,%s) called." %(a, b))return a +b

myfunc(1, 2)

myfunc(3, 4)

E:\>py -3 a.py

before myfunc() called.

myfunc(1,2) called.

after myfunc() called. result: 3

before myfunc() called.

myfunc(3,4) called.

after myfunc() called. result: 7

第六步:对参数数量不确定的函数进行装饰

'''示例6: 对参数数量不确定的函数进行装饰,

参数用(*args, **kwargs),自动适应变参和命名参数'''

defdeco(func):def _deco(*args, **kwargs):print ("before %s called." % func.__name__)

ret= func(*args, **kwargs)print ("after %s called. result: %s" % (func.__name__, ret))returnretreturn_deco

@decodefmyfunc(a, b):print ("myfunc(%s,%s) called." %(a, b))return a+b

@decodefmyfunc2(a, b, c):print ("myfunc2(%s,%s,%s) called." %(a, b, c))return a+b+c

myfunc(1, 2)

myfunc(3, 4)

myfunc2(1, 2, 3)

myfunc2(3, 4, 5)

E:\>py -3 a.py

before myfunc called.

myfunc(1,2) called.

after myfunc called. result: 3

before myfunc called.

myfunc(3,4) called.

after myfunc called. result: 7

before myfunc2 called.

myfunc2(1,2,3) called.

after myfunc2 called. result: 6

before myfunc2 called.

myfunc2(3,4,5) called.

after myfunc2 called. result: 12

第七步:被装饰函数加参数:带参数的装饰器本质都是两层闭包

'''示例7: 在示例4的基础上,让装饰器带参数,

和上一示例相比在外层多了一层包装。

装饰函数名实际上应更有意义些'''

defdeco(arg):def_deco(func):def __deco():print ("before %s called [%s]." % (func.__name__, arg))

func()print ("after %s called [%s]." % (func.__name__, arg))return __deco

return_deco

@deco("mymodule")defmyfunc():print ("myfunc() called.")

@deco("module2")defmyfunc2():print ("myfunc2() called.")

myfunc()

myfunc2()

'''

1)多了一步:deco("hello") ---》返回了闭包:__deco+s

deco=闭包:__deco+s

2)@deco--->__deco(func)+s--->返回了一个闭包_deco+func+s

后面的过程跟上一步的过程一样。

'''

E:\>py -3 a.py

before myfunc called [mymodule].

myfunc() called.

after myfunc called [mymodule].

before myfunc2 called [module2].

myfunc2() called.

after myfunc2 called [module2].

第八步:让装饰器带 类 参数

'''示例8: 装饰器带类参数'''

classlocker:def __init__(self):print ("locker.__init__() should be notcalled.")

@staticmethoddefacquire():print ("locker.acquire() called.(这是静态方法)")

@staticmethoddefrelease():print ("locker.release() called.(不需要对象实例)")defdeco(cls):'''cls 必须实现acquire和release静态方法'''

def_deco(func):def __deco():print("before %s called [%s]." %(func.__name__, cls))

cls.acquire()try:returnfunc()finally:

cls.release()return __deco

return_deco

@deco(locker)defmyfunc():print ("myfunc() called.")

myfunc()

myfunc()

E:\>py -3 a.py

before myfunc called [].

locker.acquire() called.(这是静态方法)

myfunc() called.

locker.release() called.(不需要对象实例)

before myfunc called [].

locker.acquire() called.(这是静态方法)

myfunc() called.

locker.release() called.(不需要对象实例)

第九步:装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器

'''mylocker.py: 公共类 for 示例9.py'''

classmylocker:def __init__(self):print("mylocker.__init__() called.")

@staticmethoddefacquire():print("mylocker.acquire() called.")

@staticmethoddefunlock():print("mylocker.unlock() called.")classlockerex(mylocker):

@staticmethoddefacquire():print("lockerex.acquire() called.")

@staticmethoddefunlock():print("lockerex.unlock() called.")deflockhelper(cls):'''cls 必须实现acquire和release静态方法'''

def_deco(func):def __deco(*args, **kwargs):print("before %s called." %func.__name__)

cls.acquire()try:return func(*args, **kwargs)finally:

cls.unlock()return __deco

return _deco

'''示例9: 装饰器带类参数,并分拆公共

类到其他py文件中

同时演示了对一个函数应用多个装饰

器'''

from mylocker import *

classexample:

@lockhelper(mylocker)defmyfunc(self):print ("myfunc() called.")

@lockhelper(mylocker)

@lockhelper(lockerex)defmyfunc2(self, a, b):print ("myfunc2() called.")return a +bif __name__=="__main__":

a=example()

a.myfunc()print(a.myfunc())print (a.myfunc2(1, 2))print (a.myfunc2(3, 4))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/550402.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php 日期 间隔,PHP实现计算日期间隔天数的方法

这篇文章主要介绍了PHP编程计算日期间隔天数的方法,涉及php日期与时间的转换与运算相关操作技巧,需要的朋友可以参考下刚开始在没有查PHP手册的情况下,用比较老套方法也折腾出来了,代码是这样子实现的:$date_1 date(Y-m-d);$date_2 2012-07-…

Vue02 -- 生命周期

<!DOCTYPE html> <html> <head><title>Vue --- 生命周期</title></head><body><div id"app"><input type"text" name"" v-model"a" placeholder"你的名字"><h1&g…

php 删除上传文件,php实现文件上传、下载和删除的方法

这篇文章主要为大家详细介绍了php文件上传、下载和删除示例,具有一定的参考价值&#xff0c;感兴趣的小伙伴们可以参考一下php文件上传、下载和删除示例大体思路如下&#xff0c;具体内容如下一.文件上传1.把上传文件的区域做出来p12.把显示文件的区域做出来p23.提交表单&#…

软件工程详细设计说明书_软件工程导论知识点梳理之简答题

1. 软件危机的表现形式对软件开发成本和进度估计不准确已完成的软件不符合用户需求软件产品质量差&#xff0c;可靠性得不到保证软件产品可维护性差软件成本在计算机总成本中的比例逐渐变大软件开发生产率提高速度比不上计算机应用速度2. 产生软件危机的原因(1)软件是计算机系统…

css中absolute设置问题和如何让div居中

今天设置多个div到页面正中间的时候&#xff0c;在第一层<div class"map">中设置如下&#xff1a; .map{ position&#xff1a;absolute&#xff1b; top:50%; left:50% transform: translate(-50%, -50%); } 该div就移到页面的正中间&#xff0c;达到预定效果…

php模板意思,php中的 是什么意思

php调用类的内部静态成员&#xff0c;或者是类之间调用就要用两个冒号(::)。说明&#xff1a;“::”符号可以认为是与C语言中的“.”相似的&#xff0c;而它更像C中(Perl)的::类范围操作符。示例&#xff1a;{$0;(){//}(){();$;}};/*C语言中的*/a::b::c();//C中的函数$a::b::c;…

程序员为什么老得快_这段 Python 代码让程序员赚 300W,公司已确认!网友:神操作!...

点击上方“Python大本营”&#xff0c;选择“置顶公众号”python大本营 IT人的职业提升平台Python到底还能给人多少惊喜&#xff1f;笔者最近看到了这两天关于Python最热门的话题&#xff0c;关于《地产大佬潘石屹学Python的原因》&#xff0c;结果被这个回答惊到了&#xff1…

Mercedes-Benz won’t start| Step by Step Troubleshooting Guide

Mercedes won’t start or turn over? Are you experiencing Mercedes-Benz no start problems? Key won’t turn at all? Engine turning over but the car will not start? Maybe it finally starts, runs for a few seconds and then dies. These are common Mercedes-…

php如何设置页面布局,excel页面布局怎么调整

excel页面布局调整的方法&#xff1a;首先点击菜单的页面布局&#xff0c;选择纸张大小&#xff1b;然后点击“纸张方向”&#xff0c;单击以选择横向或者纵向&#xff1b;最后点击“页边距”即可。点击菜单——页面布局&#xff0c;工具栏将出现页面布局的许多项目&#xff0c…

无法获取未定义或 null 引用的属性“value”_SpringBoot之Spring@Value属性注入使用详解

在使用Spring框架的项目中&#xff0c;Value是使用比较频繁的注解之一&#xff0c;它的作用是将配置文件中key对应的值赋值给它标注的属性。在日常使用中我们常用的功能都比较简单&#xff0c;本篇文章系统的带大家来了解一下Value的使用方法。Value注入支持形式Value属性注入功…

0x11 栈

【例题】Push,Pop,GetMin 手写一个栈 1 #include <iostream>2 #include <cstdio>3 #include <cmath>4 #include <cstring>5 #include <algorithm>6 #include <queue>7 using namespace std;8 const int maxn1000000;9 int stack[maxn], m[…

java war包合并,使用maven warpath插件合并多module的war包

查看原文&#xff1a;http://www.yeetrack.com/?p899现在java项目一般使用maven、gradle等工具来管理jar包、打包、发布。如果一个项目有很多模块&#xff0c;那般是分成多个module&#xff0c;主目录有个parent&#xff0c;负责包含全部的module&#xff0c;然后目录中多个mo…

儿童编程python入门_儿童编程python入门

经常会有小朋友问我&#xff0c;“我想做个黑客&#xff0c;我该学什么编程语言&#xff1f;”&#xff0c;或者有的小朋友会说&#xff1a;“我要学c&#xff0c;我要做病毒”。其实对于这些小朋友而言他们基本都没有接触过编程语言&#xff0c;只是通过影视或者其他地方看到的…

ARM GNU 常用汇编伪指令介绍

abort.abort: 停止汇编 .align absexpr1, absexpr2: 以某种对齐方式,在未使用的存储区域填充值. 第一个值表示对齐方式,4, 8,16 或 32. 第 二个表达式值表示填充的值. if...else...endif.if .else .endif: 支持条件预编译 include.include "file": 包含指定的头文件,…

java 同类型转换失败,你们见过java类型转换,自己转自己失败的情况吗?很神奇的操作...

问题就是上面这个问题。List slaughterProducts slaughterForm.getSlaughterProductModelForm();for (SlaughterProductModelForm e : slaughterProducts) {....}居然运行到for的时候出现上面这个错误。很神奇吧&#xff0c;工作这么多年了第一次发现 JAVA自己转自己转不成功。…

python可视化代码_python可视化实现代码

python可视化#导入两个库import numpy as npimport matplotlib.pyplot as plt#第一个参数就是x轴的初始值#第二个参数是x轴的终止值#第三个返回num均匀分布的样本&#xff0c;也就是0-12的区间取多少个点&#xff0c;如果为曲线的最好数值大一点x np.linspace(0, 12, 50)y np…

用户管理与文件权限

一&#xff1a;用户管理 现代操作系统一般属于多用户的操作系统&#xff0c;也就是说&#xff0c;同一台机器可以为多个用户建立账户&#xff0c;一般这些用户都是为普通用户&#xff0c;这些普通用户能同时登录这台计算机&#xff0c;计算机对这些用户分配一定的资源。 普通用…

php中划线,html中下划线、删除线、上划线的样式与用法实例

这篇文章主要介绍了下划线、删除线、上划线等常用的实例&#xff0c;划线是非常常见的一种样式&#xff0c;为了网页中的视觉效果以及对文字的说明&#xff0c;我们经常对文体进行一些划线操作。下面文章就是对各种划线的详细介绍。一. 下划线的详细介绍在我们日常的Web的开发中…

rabbitmq3.7集群搭建实战

环境&#xff1a; 3台 centos7.4rabbitmq3.7erlang 22 1. 有几种方式安装&#xff0c;这里使用的yum安装&#xff08;官方推荐&#xff09;2. 使用rabbitmq时需要安装erlang&#xff0c;在各个节点上使用vim添加两个repo文件**/etc/yum.repos.d/rabbitmq_erlang.repo**[rabbitm…

php获取页面中的指定内容,php 获取页面中指定内容的实现类

[email protected]image&#xff1a;Grep.class.php/** grep class* Date: 2013-06-15* Author: fdipzone* Ver: 1.0** Func:** set: 设置内容* get: 返回指定的内容* replace: 返回替换后的内容* get_pattern 根据type返回pattern*/class Grep{ // class startprivate $_patte…