Python闭包与装饰器原理及实例解析


Posted in Python onApril 30, 2020

一、闭包

闭包相当于函数中,嵌套另一个函数,并返回。代码如下:

def func(name): # 定义外层函数
  def inner_func(age): # 内层函数
    print('name: ', name, ', age: ', age)
  return inner_func # 注意此处要返回,才能体现闭包

bb = func('jayson') # 将字符串传给func函数,返回inner_func并赋值给变量
bb(28) # 通过变量调用func函数,传入参数,从而完成闭包
>>
name: jayson , age: 28

二、装饰器

装饰器:把函数test当成变量传入装饰函数deco --> 执行了装饰操作后,变量传回给了函数test()。比如装饰器效果是test = test-1,test函数经过deco装饰后,调用test其实执行的是 test = test-1。

1、装饰器是利用闭包原理,区别是装饰器在闭包中传入的参数是函数,而不是变量。

注:其实在装饰器中,函数即变量

def deco(func): # 传入func函数。
  print('decoration')
  return func
def test():
  print('test_func')

test = deco(test) # 对函数进行装饰。执行了deco函数,并将返回值赋值给test
>>
# 输出deco的运行结果
decoration

test() # 运行装饰后的函数
>>
test_func

2、以上代码等价于

def deco(func): # 传入func函数。
  print('decoration')
  return func

@deco # 等价于上一代码中test = deco(test),不过上一代码需放在定义test之后
def test():
  print('test_func')

>>
# 输出deco的运行结果
decoration

test() # 运行装饰后的函数
>>
test_func

3、装饰器(简版)

def deco(func): # 装饰函数传入func
  print('decoration')
  return func

@deco # 装饰函数。
def test():
  print('test_func') 
# 定义完函数后,会直接执行装饰器deco(test)
>>
decoration

# 调用test,执行test函数
test()
>> 
test_func

3、装饰器(升级版)

在上一个版本中,由于在定义装饰器 + 函数时,就会执行装饰函数里面的语句。

为了使其在未被调用时候不执行,需要再嵌套一个函数,将函数进行包裹。

def deco(func): 
  print('decoration') # 此处未调用func函数时,会直接执行
  def wrapper(): # 名称自定义,一般用wrapper
    print('execute') # 此处未调用func函数时,不会执行
    func() # 执行函数
  return wrapper # 此处返回wrapper给func,通过外部func()执行

@deco # 注意:此处不能有括号。有括号的形式是func未传入最外层deco(),传入deco的子函数中
def test():
  print('test_func')
>>
decoration
#调用test
test()
>>
execute
test_func

注意:如果func函数本身有返回值,同样需要在包裹函数中返回

def deco(func): 
  print('decoration')
  def wrapper():
    print('execute')
    a = func() # 执行函数,并返回值
    print('done')
    return a # 将func的返回值一并返回
  return wrapper

@deco
def test():
  print('test_func')
  return 5 # 增加返回值
>>
decoration

#调用test
test()
>>
execute
test_func
done
 # 此处是test函数的返回值

3、装饰器(进阶版)

在包裹函数中,参数形式设置为*arg、**kwarg,会使得函数更加灵活。

当修改test函数参数形式时,不用在装饰器中同时修改。

import time

def deco(func):
  def inner(*arg, **kwarg): # 此处传入参数
    begin_time = time.time()
    time.sleep(2)
    a = func(*arg, **kwarg) # 调用函数,使用传入的参数
    end_time = time.time()
    print('运行时间:', end_time - begin_time)
    return a
  return inner

@deco
def test(a):
  print('test function:', a)
  return a

# 调用函数
test(5)
>>
test function: 5
运行时间: 2.0003252029418945
 # 5是函数返回的值

4、高阶版

有时候我们会发现有的装饰器带括号,其原因是将上述的装饰器外面又套了一个函数

import time

def outer(): # 在原装饰器外套一层函数,将装饰器封装在函数里面。(outer自定义)
  def deco(func): # 原装饰器,后面的代码一样
    def inner(*arg, **kwarg): 
      begin_time = time.time()
      time.sleep(2)
      a = func(*arg, **kwarg) 
      end_time = time.time()
      print('运行时间:', end_time - begin_time)
      return a
    return inner
  return deco # 注意:此处需返回装饰函数

@outer() # 此处就需要加括号,其实是调用了outer()函数,将test传进其子函数
def test(a):
  print('test function:', a)
  return a

test(4)
>>
test function: 4
运行时间: 2.000566005706787
 # 返回4

5、高阶终结版

带参数的装饰器(装饰器加括号,带参数)

import time

def outer(choose): # 在最外层函数中加入参数
  if choose==1: # 通过choose参数,选择装饰器
    def deco(func):
      def inner(*arg, **kwarg):
        print('decoration1')
        begin_time = time.time()
        time.sleep(2) # 睡眠2s
        a = func(*arg, **kwarg) 
        end_time = time.time()
        print('运行时间1:', end_time - begin_time)
        return a
      return inner
    return deco
  
  else:
    def deco(func):
      def inner(*arg, **kwarg): 
        print('decoration2')
        begin_time = time.time()
        time.sleep(5) # 睡眠5s
        a = func(*arg, **kwarg) 
        end_time = time.time()
        print('运行时间2:', end_time - begin_time)
        return a
      return inner
    return deco

@outer(1) # 由于outer中有参数,此处必须传入参数
def test1(a):
  print('test function1:', a)
  return a

@outer(5) # 传入另一个参数
def test2(a):
  print('test function2:', a)
  return a


# 分别调用2个函数(2个函数装饰器相同,装饰器参数不同)
test1(2) # 调用test1
>>
decoration1
test function1: 2
运行时间1: 2.000072717666626 # 2秒
 # test1的返回值

test2(4) # 调用test2
>>
decoration2
test function2: 4
运行时间2: 5.000797986984253 # 5秒
 # test2的返回值

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python搭建FTP服务器的方法示例
Jan 19 Python
python微信跳一跳系列之棋子定位像素遍历
Feb 26 Python
Numpy数组转置的两种实现方法
Apr 17 Python
python腾讯语音合成实现过程解析
Aug 01 Python
基于python 微信小程序之获取已存在模板消息列表
Aug 05 Python
在python3中实现更新界面
Feb 21 Python
Python导入模块包原理及相关注意事项
Mar 25 Python
python3用PyPDF2解析pdf文件,用正则匹配数据方式
May 12 Python
基于python模拟bfs和dfs代码实例
Nov 19 Python
Python函数式编程中itertools模块详解
Sep 15 Python
Python 正则模块详情
Nov 02 Python
基于Python编写一个监控CPU的应用系统
Jun 25 Python
python+requests接口压力测试500次,查看响应时间的实例
Apr 30 #Python
Pycharm连接远程服务器过程图解
Apr 30 #Python
python3发送request请求及查看返回结果实例
Apr 30 #Python
python获取响应某个字段值的3种实现方法
Apr 30 #Python
如何在python中执行另一个py文件
Apr 30 #Python
在Ubuntu 20.04中安装Pycharm 2020.1的图文教程
Apr 30 #Python
Python实现转换图片背景颜色代码
Apr 30 #Python
You might like
php使用CURL伪造IP和来源实例详解
2015/01/15 PHP
PHP如何使用cURL实现Get和Post请求
2020/07/11 PHP
js实现的复制兼容chrome和IE
2014/04/03 Javascript
Express作者TJ告别Node.js奔向Go
2014/07/14 Javascript
NodeJS学习笔记之网络编程
2014/08/03 NodeJs
JavaScript控制listbox列表框的项目上下移动的方法
2015/03/18 Javascript
js不间断滚动的简单实现
2016/06/03 Javascript
jQuery插件扩展操作入门示例
2017/01/16 Javascript
JS实现选定指定HTML元素对象中指定文本内容功能示例
2017/02/13 Javascript
jQuery操作DOM_动力节点Java学院整理
2017/07/04 jQuery
Node.js如何对SQLite的async/await封装详解
2019/02/14 Javascript
Nuxt.js实战和配置详解
2019/08/05 Javascript
vue下的@change事件的实现
2019/10/25 Javascript
Vue如何基于es6导入外部js文件
2020/05/15 Javascript
解决vue中的无限循环问题
2020/07/27 Javascript
[01:15:45]DOTA2上海特级锦标赛B组小组赛#1 Alliance VS Spirit第一局
2016/02/26 DOTA
[01:45:05]VGJ.T vs Newbee Supermajor 败者组 BO3 第二场 6.6
2018/06/07 DOTA
Python 列表排序方法reverse、sort、sorted详解
2016/01/22 Python
python基于隐马尔可夫模型实现中文拼音输入
2016/04/01 Python
python基础教程项目二之画幅好画
2018/04/02 Python
Python 利用高德地图api实现经纬度与地址的批量转换
2019/08/14 Python
python定义类self用法实例解析
2020/01/22 Python
PyCharm 2020.2下配置Anaconda环境的方法步骤
2020/09/23 Python
python 爬取百度文库并下载(免费文章限定)
2020/12/04 Python
python字典按照value排序方法
2020/12/28 Python
详解如何修改jupyter notebook的默认目录和默认浏览器
2021/01/24 Python
HTML5 visibilityState属性详细介绍和使用实例
2014/05/03 HTML / CSS
英国领先的办公用品供应商:Viking
2016/08/01 全球购物
PHP面试题-$message和$$message的区别
2015/12/08 面试题
String s = new String(“xyz”);创建了几个String Object?
2015/08/05 面试题
迟到检讨书5000字
2014/01/31 职场文书
空乘英文求职信
2014/04/13 职场文书
美术课外活动总结
2014/07/08 职场文书
生日答谢词
2015/01/05 职场文书
检讨书范文300字
2015/01/28 职场文书
vue中this.$http.post()跨域和请求参数丢失的解决
2022/04/08 Vue.js