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利用pyHook实现监听用户鼠标与键盘事件
Aug 21 Python
简单介绍Python中的JSON模块
Apr 08 Python
在Docker上开始部署Python应用的教程
Apr 17 Python
给你选择Python语言实现机器学习算法的三大理由
Nov 15 Python
Python基于多线程实现抓取数据存入数据库的方法
Jun 22 Python
python实现对csv文件的列的内容读取
Jul 04 Python
使用Python AIML搭建聊天机器人的方法示例
Jul 09 Python
Python实现字典按key或者value进行排序操作示例【sorted】
May 03 Python
python3用PIL把图片转换为RGB图片的实例
Jul 04 Python
Django中modelform组件实例用法总结
Feb 10 Python
python设置表格边框的具体方法
Jul 17 Python
一篇文章带你了解Python和Java的正则表达式对比
Sep 15 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
phpMyAdmin下载、安装和使用入门教程
2007/05/31 PHP
php设计模式  Command(命令模式)
2011/06/17 PHP
PHP常用函数和常见疑难问题解答
2014/03/05 PHP
PHP对接微信公众平台消息接口开发流程教程
2014/03/25 PHP
php实现的zip文件内容比较类
2014/09/24 PHP
php结合mysql与mysqli扩展处理事务的方法
2016/06/29 PHP
基于PHP微信红包的算法探讨
2016/07/21 PHP
VSCode+PHPstudy配置PHP开发环境的步骤详解
2020/08/20 PHP
仿当当网淘宝网等主流电子商务网站商品分类导航菜单
2013/09/25 Javascript
jQuery中width()方法用法实例
2014/12/24 Javascript
JS仿iGoogle自定义首页模块拖拽特效的方法
2015/02/13 Javascript
jQuery下拉美化搜索表单效果代码分享
2015/08/25 Javascript
vue实现在表格里,取每行的id的方法
2018/03/09 Javascript
vuejs中监听窗口关闭和窗口刷新事件的方法
2018/09/21 Javascript
移动端图片上传旋转、压缩问题的方法
2018/10/16 Javascript
微信小程序添加插屏广告并设置显示频率(一天一次)
2019/12/06 Javascript
vue实现把接口单独存放在一个文件方式
2020/08/13 Javascript
[01:20:06]TNC vs VG 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
Django中的“惰性翻译”方法的相关使用
2015/07/27 Python
Python中list初始化方法示例
2016/09/18 Python
Python清空文件并替换内容的实例
2018/10/22 Python
Python模块的加载讲解
2019/01/15 Python
详解Python传入参数的几种方法
2019/05/16 Python
Python读取二进制文件代码方法解析
2020/06/22 Python
Python Process创建进程的2种方法详解
2021/01/25 Python
CSS3制作炫酷的自定义发光文字
2016/03/28 HTML / CSS
美国时尚配饰品牌:Dooney & Bourke
2017/11/14 全球购物
保密工作实施方案
2014/02/24 职场文书
高中生班主任评语
2014/04/25 职场文书
2014年科室工作总结
2014/11/20 职场文书
2015年五四青年节演讲稿
2015/03/18 职场文书
计算机专业自荐信范文
2015/03/26 职场文书
贫困证明书范文
2015/06/16 职场文书
《假如》教学反思
2016/02/17 职场文书
Python基本数据类型之字符串str
2021/07/21 Python
台式电脑蓝牙适配器怎么安装?台式电脑蓝牙适配器安装教程
2022/04/08 数码科技