Python闭包和装饰器用法实例详解


Posted in Python onMay 22, 2019

本文实例讲述了Python闭包和装饰器用法。分享给大家供大家参考,具体如下:

Python的装饰器的英文名叫Decorator,作用是完成对一些模块的修饰。所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去。

闭包

1.函数引用

#coding=utf-8
def test1():
  print('This is test1!')
#调用函数
test1()
#引用函数
ret = test1
#打印id
print('test1\t的地址:',id(test1))
print('ret\t\t的地址:',id(ret))
print('你会发现test1的地址和ret的地址是一样的!')
#通过引用调用函数
ret()

运行结果:

This is test1!
test1   的地址: 139879303947128
ret     的地址: 139879303947128
你会发现test1的地址和ret的地址是一样的!
This is test1!

1. 什么是闭包

在嵌套函数中,内部函数用到了外部函数的变量,则

称内部函数为闭包。

python中的闭包从表现形式上定义(解释)为:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure).

上代码:

#coding=utf-8
def outer(num):
  def inner(num_in):
    return num + num_in
  return inner
#10赋值给了num
ret = outer(10)
#20赋值给了num_in
print('ret(20) = ',ret(20))
#30赋值给了num_in
print('ret(30) = ',ret(30))

运行结果:

ret(20) =  30
ret(30) =  40

闭包的应用例子一:

看代码:

#coding=utf-8
def line_conf(a, b):
  def line(x):
    return a*x + b
  return line
line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
print(line1(5))
print(line2(5))

运行结果:

6
25

这个例子中,函数line与变量a,b构成闭包。在创建闭包的时候,我们通过line_conf的参数a,b说明了这两个变量的取值,这样,我们就确定了函数的最终形式(y = x + 1和y = 4x + 5)。我们只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,闭包也具有提高代码可复用性的作用。

如果没有闭包,我们需要每次创建直线函数的时候同时说明a,b,x。这样,我们就需要更多的参数传递,也减少了代码的可移植性。

闭包思考:

1.闭包似优化了变量,原来需要类对象完成的工作,闭包也可以完成。
2.由于闭包引用了外部函数的局部变量,则外部函数的局部变量没有及时释放,消耗内存。

代码如下:

#coding=utf-8
#定义函数:完成包裹数据
def makeBold(func):
  def wrapped():
    return "<b>" + func() + "</b>"
  return wrapped
#定义函数:完成包裹数据
def makeItalic(fn):
  def wrapped():
    return "<i>" + fn() + "</i>"
  return wrapped
@makeBold
def test1():
  return "hello world-1"
@makeItalic
def test2():
  return "hello world-2"
@makeBold
@makeItalic
def test3():
  return "hello world-3"
print(test1())
print(test2())
print(test3())

运行结果:

<b>hello world-1</b>
<i>hello world-2</i>
<b><i>hello world-3</i></b>

装饰器(decorator)功能

1. 引入日志
2. 函数执行时间统计
3. 执行函数前预备处理
4. 执行函数后清理功能
5. 权限校验等场景
6. 缓存

装饰器示例

例1:无参数的函数

代码如下:

#coding=utf-8
from time import ctime, sleep
def time_func(func):
  def wrapped_func():
    print('%s call at %s'%(func.__name__, ctime()))
    func()
  return wrapped_func
@time_func
def foo():
  print('i am foo!')
foo()
sleep(2)
foo()

运行结果:

foo call at Thu Aug 24 21:32:39 2017
i am foo!
foo call at Thu Aug 24 21:32:41 2017
i am foo!

例2:被装饰的函数有参数

#coding=utf-8
from time import ctime, sleep
def timefunc(func):
  def wrappedfunc(a, b):
    print('%s called at %s'%(func.__name__, ctime()))
    print(a, b)
    func(a, b)
  return wrappedfunc
@timefunc
def foo(a,b):
  print(a+b)
foo(3,5)
sleep(2)
foo(2,4)

运行结果:

foo called at Thu Aug 24 21:40:20 2017
3 5
8
foo called at Thu Aug 24 21:40:22 2017
2 4
6

例3:被装饰的函数有不定长参数

#coding=utf-8
from time import ctime, sleep
def timefunc(func):
  def wrappedfunc(*args, **kwargs):
    print('%s called at %s'%(func.__name__, ctime()))
    func(*args, **kwargs)
  return wrappedfunc
@timefunc
def foo(a,b,c):
  print(a+b+c)
foo(3,5,7)
sleep(2)
foo(2,4,9)

运行结果:

foo called at Thu Aug 24 21:45:13 2017
15
foo called at Thu Aug 24 21:45:15 2017
15

例4:装饰器中的return

如下:

#coding=utf-8
from time import ctime
def timefunc(func):
  def wrappedfunc():
    print('%s called at %s'%(func.__name__, ctime()))
    func()
  return wrappedfunc
@timefunc
def getInfo():
  return '---hello---'
info = getInfo()
print(info)

代码如下:

getInfo called at Thu Aug 24 21:59:26 2017
None

如果修改装饰器为 return func():

如下:

#coding=utf-8
from time import ctime
def timefunc(func):
  def wrappedfunc():
    print('%s called at %s'%(func.__name__, ctime()))
    return func()
  return wrappedfunc
@timefunc
def getInfo():
  return '---hello---'
info = getInfo()
print(info)

代码如下:

getInfo called at Thu Aug 24 22:07:12 2017
---hello---

总结:

一般情况下为了让装饰器更通用,可以有return

例5:装饰器带参数,在原有装饰器的基础上,设置外部变量

#coding=utf-8
from time import ctime, sleep
def timefun_arg(pre="hello"):
  def timefunc(func):
    def wrappedfunc():
      print('%s called at %s'%(func.__name__, ctime()))
      return func()
    return wrappedfunc
  return timefunc
@timefun_arg('hello')
def foo1():
  print('i am foo')
@timefun_arg('world')
def foo2():
  print('i am foo')
foo1()
sleep(2)
foo1()
foo2()
sleep(2)
foo2()

运行结果:

foo1 called at Thu Aug 24 22:17:58 2017
i am foo
foo1 called at Thu Aug 24 22:18:00 2017
i am foo
foo2 called at Thu Aug 24 22:18:00 2017
i am foo
foo2 called at Thu Aug 24 22:18:02 2017
i am foo

可以理解为:

foo1()==timefun_arg("hello")(foo1())
foo2()==timefun_arg("world")(foo2())

例6:类装饰器

装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重载了 call() 方法,那么这个对象就是

callable的。
class Test():
  def __call__(self):
    print('call me!')
t = Test()
t() # call me

类装饰器demo:

class Decofunc(object):
  def __init__(self, func):
    print("--初始化--")
    self._func = func
  def __call__(self):
    print('--装饰器中的功能--')
    self._func()
@Decofunc
def showpy():
  print('showpy')
showpy()#如果把这句话注释,重新运行程序,依然会看到"--初始化--"

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python中的rfind()方法使用详解
May 19 Python
python监控文件或目录变化
Jun 07 Python
使用Python编写一个最基础的代码解释器的要点解析
Jul 12 Python
浅谈Python 对象内存占用
Jul 15 Python
python字典操作实例详解
Nov 16 Python
Python中一行和多行import模块问题
Apr 01 Python
Jupyter中直接显示Matplotlib的图形方法
May 24 Python
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
Dec 04 Python
Python中join()函数多种操作代码实例
Jan 13 Python
Python如何将模块打包并发布
Aug 30 Python
Python 调用C++封装的进一步探索交流
Mar 04 Python
Pytorch 实现变量类型转换
May 17 Python
Python进程间通信Queue消息队列用法分析
May 22 #Python
将python文件打包成EXE应用程序的方法
May 22 #Python
Python多线程threading模块用法实例分析
May 22 #Python
Python3之手动创建迭代器的实例代码
May 22 #Python
PyTorch搭建一维线性回归模型(二)
May 22 #Python
PyTorch基本数据类型(一)
May 22 #Python
PyTorch搭建多项式回归模型(三)
May 22 #Python
You might like
Ajax+PHP 边学边练之四 表单
2009/11/27 PHP
基于initPHP的框架介绍
2013/04/18 PHP
php模拟post提交数据的方法
2015/02/12 PHP
搭建基于Docker的PHP开发环境的详细教程
2015/07/01 PHP
windows7配置Nginx+php+mysql的详细教程
2016/09/04 PHP
php中遍历二维数组并以表格的形式输出的方法
2017/01/03 PHP
thinkphp5.1框架容器与依赖注入实例分析
2019/07/23 PHP
JavaScript 解析读取XML文档 实例代码
2009/07/07 Javascript
jQuery创建自己的插件(自定义插件)的方法
2010/06/10 Javascript
javascript动画之圆形运动,环绕鼠标运动作小球
2010/07/20 Javascript
麻雀虽小五脏俱全 Dojo自定义控件应用
2010/09/04 Javascript
jQuery下通过$.browser来判断浏览器.
2011/04/05 Javascript
jQuery.clean使用方法及思路分析
2013/01/07 Javascript
javascript实现确定和取消提示框效果
2015/07/10 Javascript
CSS3实现动态背景登录框的代码
2015/07/28 Javascript
JS函数arguments数组获得实际传参数个数的实现方法
2016/05/28 Javascript
完美解决JS文件页面加载时的阻塞问题
2016/12/18 Javascript
js实现图片放大展示效果
2017/08/30 Javascript
Node.js学习之TCP/IP数据通讯(实例讲解)
2017/10/11 Javascript
JS和Canvas实现图片的预览压缩和上传功能
2018/03/30 Javascript
JavaScript Array对象基本方法详解
2019/09/03 Javascript
JavaScript算法学习之冒泡排序和选择排序
2019/11/02 Javascript
Chrome插件开发系列一:弹窗终结者开发实战
2020/10/02 Javascript
vue使用echarts画组织结构图
2021/02/06 Vue.js
[01:38]女王驾到——至宝魔廷新尊技能&特效展示
2020/06/16 DOTA
Python获取邮件地址的方法
2015/07/10 Python
Python中使用bidict模块双向字典结构的奇技淫巧
2016/07/12 Python
Python 实现 贪吃蛇大作战 代码分享
2016/09/07 Python
利用python模拟sql语句对员工表格进行增删改查
2017/07/05 Python
Python排序搜索基本算法之插入排序实例分析
2017/12/11 Python
Django自定义全局403、404、500错误页面的示例代码
2020/03/08 Python
HTML5 video 视频标签使用介绍
2014/02/03 HTML / CSS
精选鞋类、服装和配饰的全球领先目的地:Bodega
2021/02/27 全球购物
厨房管理计划书
2014/04/27 职场文书
关爱空巢老人感想
2015/08/11 职场文书
一条慢SQL语句引发的改造之路
2022/03/16 MySQL