谈一谈Python中的装饰器

news2024/9/27 9:30:29

1、装饰器基础介绍

1.1 何为Python中的装饰器?

Python中装饰器的定义以及用途:

装饰器是一种特殊的函数,它可以接受一个函数作为参数,并返回一个新的函数。装饰器可以用来修改或增强函数的行为,而不需要修改函数本身的代码。在Python中,装饰器通常用于实现AOP(面向切面编程),例如日志记录、性能分析、缓存等。装饰器的语法使用@符号,将装饰器函数放在被装饰函数的定义之前

学过设计模式的朋友都知道,设计模式的结构型模式中也有一个叫装饰器模式,那这个和Python中的装饰器有什么不同呢?

设计模式中的装饰器的定义以及用途:

设计模式中的装饰器是一种结构型模式,它可以在不改变原对象的情况下,为对象添加额外的功能。装饰器模式通常用于在运行时动态地为对象添加功能,而不是在编译时静态地为对象添加功能。装饰器模式通常涉及到多个对象之间的协作,而不是单个函数或对象。

因此,Python中的装饰器和设计模式中的装饰器虽然名称相同,但是它们的实现方式和应用场景有很大的不同。

1.2 闭包

那Python种的装饰器是怎么实现的呢?先不用着急,我们先来一起学习学习Python中的闭包。

那什么叫做闭包呢?

闭包是指一个函数和它所在的环境变量的组合,即在函数内部定义的函数可以访问外部函数的变量和参数,即使外部函数已经返回。闭包可以用来实现函数式编程中的柯里化、惰性求值、函数组合等高级特性。

看着上面的文字,是不是感觉有点抽象。我说一说我对闭包的理解

闭包是由外部函数和内部函数,内部函数引用到了外部函数定义的变量,外部函数的返回值是内部函数的函数名。对于这样的函数,我们就称为闭包。

好像也有点抽象,我们来看一断代码,就能够理解上面的话了。

def my_decorator():  # my_decorator 这个就叫做外部函数
    a = 1
    def inner():  # inner 这个叫做内部函数
        print(a)  # 内部函数引用到了外部函数中定义的变量
    return inner  # 外部函数的返回值是内部函数名

2、函数装饰器的实现

上面讲解了装饰器的定义、用途,还有闭包,那怎么去实现一个装饰器呢?不急,接下来我们一起来学习如何实现装饰器。

装饰器不是说可以不改变一个函数源代码的基础上,给这个函数添加额外的功能吗?那怎么做呢?

接下来,我们就一起实现一个装饰器,来计算函数的执行时间。Let‘s go!

2.1 不使用@实现装饰器

首先,使用闭包定义一个统计函数执行时间的功能。

def process_time(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("函数的执行时间为:%d" % (end_time-start_time))
        return ret
    return inner

接下来定义一个函数,使用比较来计算函数的执行时间。

import time


def process_time(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("函数的执行时间为:%d" % (end_time-start_time))
        return ret
    return inner


def test(sleep_time):
    time.sleep(sleep_time)


t1 = process_time(test)
t1(1)
print("------------")
t1(2)

执行结果:

函数的执行时间为:1
------------
函数的执行时间为:2

通过上面的代码,我们观察到,我们并没有修改test函数的源代码,依旧给test函数添加上了统计函数执行时间的功能。

Python中实现上述功能,有更加优雅的方式。下面,我们就一起来看看如何实现的。

2.2 Python中使用语法糖的装饰器(推荐使用)

import time


def process_time(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("函数的执行时间为:%d" % (end_time-start_time))
        return ret
    return inner


@process_time
def test(sleep_time):
    time.sleep(sleep_time)


test(1)
print("------------")
test(2)

执行结果:

函数的执行时间为:1
------------
函数的执行时间为:2

观察上面的代码变动,发现只有很少的部分修改了。

1、test函数上面添加了一行@process_time

2、test函数的调用方式发生了改变。

其他的并没有发生变化,整个代码看起来也更加清爽了。

提示:

当使用@装饰器时,会自动执行 闭包中的外部函数内容。这个可以自行验证。

当使用@装饰器时,Python解释器为我们做了什么?

当使用@装饰器时,Python解释器会将被装饰的函数作为参数传递给装饰器函数,并将其返回值作为新的函数对象替换原来的函数对象。这样,每次调用被装饰的函数时,实际上是调用了装饰器函数返回的新函数对象。

Python 装饰器 @ 实际上是一种语法糖,它可以让我们在不改变原函数代码的情况下,对函数进行扩展或修改。当我们使用 @ 装饰器时,实际上是将被装饰函数作为参数传递给装饰器函数,然后将装饰器函数的返回值赋值给原函数名。因此,@ 装饰器并不会进行内存拷贝。

通过下面的函数,可以得知,innertest函数指向的是同一个内存地址。

import time


def process_time(func):

    print("func id --->", id(func))

    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("函数的执行时间为:%d" % (end_time - start_time))
        return ret

    print("inner id --->", id(inner))
    return inner


@process_time
def test(sleep_time):
    print("test func id --->", id(test))
    time.sleep(sleep_time)


print("test id --->", id(test))

执行结果:

func id ---> 4312377952
inner id ---> 4313983008
test id ---> 4313983008

使用语法糖时,Python解释器底层为我们做了这样的处理。

2.3 多个装饰器的执行顺序

上面的两个例子,都只有一个装饰器,是不是Python只能写一个装饰器呢。其实不是的。主要是为了讲解简单。接下来,我们一起来看看,多个装饰器的执行顺序。

def outer_1(func):
    print("coming outer_1")

    def inner_1():
        print("coming inner_1")
        func()
    return inner_1


def outer_2(func):
    print("coming outer_2")

    def inner_2():
        print("coming inner_2")
        func()

    return inner_2


def outer_3(func):
    print("coming outer_3")

    def inner_3():
        print("coming inner_3")
        func()

    return inner_3


@outer_1
@outer_2
@outer_3
def test():
    print("coming test")


test()

执行结果:

coming outer_3
coming outer_2
coming outer_1
coming inner_1
coming inner_2
coming inner_3
coming test

outer_3 -> outer_2 -> outer_1 -> inner_1 -> inner_2 -> inner_3 -> 被装饰函数

从上面的执行结果,可以得出如下结论:

使用多个装饰器装饰函数时,
外部函数的执行顺序是从下到上的。
内部函数的执行顺序是从下往上的。

多个装饰器装饰函数时,Python解释器底层做了啥

通过下面这段代码验证

def outer_1(func):
    print("coming outer_1, func id -->", id(func))

    def inner_1():
        print("coming inner_1")
        func()

    print("inner_1 id -->", id(inner_1))
    return inner_1


def outer_2(func):
    print("coming outer_2, func id -->", id(func))

    def inner_2():
        print("coming inner_2")
        func()

    print("inner_2 id -->", id(inner_2))
    return inner_2


def outer_3(func):
    print("coming outer_3, func id -->", id(func))

    def inner_3():
        print("coming inner_3")
        func()

    print("inner_3 id -->", id(inner_3))
    return inner_3


@outer_1
@outer_2
@outer_3
def test():
    print("coming test")


test()

执行结果:

coming outer_3, func id --> 4389102784
inner_3 id --> 4389102928
coming outer_2, func id --> 4389102928
inner_2 id --> 4389103072
coming outer_1, func id --> 4389103072
inner_1 id --> 4389103216
coming inner_1
coming inner_2
coming inner_3
coming test

2.4 带参数的装饰器

该如何实现带参数的装饰器呢,其实原理一样的,我们再定义一个外层函数,外层函数的返回值是内存函数的名称,即引用。

下面我们来看一个例子:

def is_process(flag):
    def outer_1(func):
        print("coming outer_1, func id -->", id(func))

        def inner_1():
            print("coming inner_1")
            if flag:
                func()

        print("inner_1 id -->", id(inner_1))
        return inner_1
    return outer_1


@is_process(True)
def test():
    print("coming test")


test()

注意:

  • 我们装饰函数时,装饰器的写法不同了,变成了@is_process(True),这里是调用了is_process这个函数

3、函数装饰器的注意点(wraps函数)

猜一猜下面函数会输出什么?

def outer_1(func):
    def inner_1():
        print("inner_1, func __name__", func.__name__)
        print("inner_1, func __doc__", func.__doc__)
        func()

    return inner_1


@outer_1
def test():
    """this is test"""
    print("outer_1, func __name__", test.__name__)
    print("outer_1, func __doc__", test.__doc__)


test()

函数执行结果:

inner_1, func __name__ test
inner_1, func __doc__ this is test
test, test __name__ inner_1
test, test __doc__ None

注意到没,在test函数体内打印函数的 __name__、__doc__ 属性,居然变成内部函数的了。

这个是为什么呢?

Python装饰器在装饰函数时,会将原函数的函数名、文档字符串、参数列表等属性复制到装饰器函数中,但是装饰器函数并不会复制原函数的所有属性。例如,原函数的name属性、doc属性、module属性等都不会被复制到装饰器函数中。

为了避免这种情况,可以使用functools库中的wraps装饰器来保留原来函数对象的属性。wraps装饰器可以将原来函数对象的属性复制到新的函数对象中,从而避免属性丢失的问题。

from functools import wraps


def outer_1(func):

    @wraps(func)
    def inner_1():
        print("inner_1, func __name__", func.__name__)
        print("inner_1, func __doc__", func.__doc__)
        func()

    return inner_1


@outer_1
def test():
    """this is test"""
    print("test, test __name__", test.__name__)
    print("test, test __doc__", test.__doc__)


test()

执行结果:

inner_1, func __name__ test
inner_1, func __doc__ this is test
test, test __name__ test
test, test __doc__ this is test

4、类装饰器

上面我们都是使用的函数来实现装饰器的功能,那可不可以用类来实现装饰器的功能呢?我们知道函数实现装饰器的原理是外部函数的参数是被装饰的函数,外部函数返回内部函数的名称。内部函数中去执行被装饰的函数。

那么其实类也是可以用来实现装饰器的,因为当我们为 类 定义了 __call__方法时,这个类就成了可调用对象,实例化后可直接调用。

class ProcessTime:

    def __call__(self, *args, **kwargs):
        print("call")


p = ProcessTime()
p()

4.1 类装饰器的实现

import time


class ProcessTime:

    def __init__(self, func):

        print("coming ProcessTime __init__")
        self.func = func

    def __call__(self, *args, **kwargs):
        start_time = time.time()
        print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
        ret = self.func(*args, **kwargs)
        end_time = time.time()
        print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
        return ret


@ProcessTime
def test(sleep_time):
    time.sleep(sleep_time)
    return "tet"


test(1)

执行结果:

coming ProcessTime __init__
coming ProcessTime __call__, id(self.func) --> 4488922160
ProcessTime 函数的执行时间为:1

通过上面的执行结果,我们可以得到,@ProcessTime的作用是 test = ProcessTime(test)。又因为 ProcessTime定义了__call__方法,是可调用对象,所以可以像函数那样直接调用实例化ProcessTime后的对象。

这里可以验证,通过注释掉装饰器,手动初始化ProcessTime类。得到的结果是一样的。

# @ProcessTime
def test(sleep_time):
    time.sleep(sleep_time)
    return "tet"


test = ProcessTime(test)
test(1)

4.2 多个类装饰器的执行顺序

多个类装饰器的执行顺序是怎么样的呢,这里我们也通过代码来进行验证。

import time


class ProcessTime:

    def __init__(self, func):

        print("coming ProcessTime __init__", id(self))
        self.func = func

    def __call__(self, *args, **kwargs):
        start_time = time.time()
        print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
        ret = self.func(*args, **kwargs)
        end_time = time.time()
        print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
        return ret


class ProcessTime2:

    def __init__(self, func):
        print("coming ProcessTime2 __init__", id(self))
        self.func = func

    def __call__(self, *args, **kwargs):
        start_time = time.time()
        print("coming ProcessTime2 __call__, id(self.func) -->", id(self.func))
        ret = self.func(*args, **kwargs)
        end_time = time.time()
        print("ProcessTime2 函数的执行时间为:%d" % (end_time - start_time))
        return ret


@ProcessTime
@ProcessTime2
def test(sleep_time):
    time.sleep(sleep_time)
    return "tet"


# test = ProcessTime2(test)
# test = ProcessTime(test)

t = test(1)

执行结果:

coming ProcessTime2 __init__ 4472235104
coming ProcessTime __init__ 4473162672
coming ProcessTime __call__, id(self.func) --> 4472235104
coming ProcessTime2 __call__, id(self.func) --> 4471735344
ProcessTime2 函数的执行时间为:1
ProcessTime 函数的执行时间为:1

从上面的结果,我们得到,执行顺序是:

ProcessTime2 中的__init__ -> ProcessTime 中的__init__ -> ProcessTime 中的__call__ -> ProcessTime2 中的__call__

特别注意:

ProcessTime 中的__call__ 中的代码并不会执行完后再去执行 ProcessTime2 中的__call__,而是在调用 ret = self.func(*args, **kwargs) 方法后,就回去执行 ProcessTime2 中的__call__的代码。

4.3 类装饰器存在的问题

其实,类装饰器也存在和函数装饰器一样的问题。它会覆盖原函数的元数据信息,例如函数名、文档字符串、参数列表等。这可能会导致一些问题,例如调试时无法正确显示函数名、文档生成工具无法正确生成文档等。

import time
from functools import wraps


class ProcessTime:

    def __init__(self, func):

        print("coming ProcessTime __init__", id(self))
        self.func = func

    def __call__(self, *args, **kwargs):
        start_time = time.time()
        print("coming ProcessTime __call__, id(self.func) -->", id(self.func))

        ret = self.func(*args, **kwargs)
        end_time = time.time()
        print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
        return ret
        

@ProcessTime
def test(sleep_time):
    "tets"
    print("test.__doc__", test.__doc__)
    # print(test.__name__)  --> 报错,AttributeError: 'ProcessTime' object has no attribute '__name__'
    time.sleep(sleep_time)
    return "tet"
  

t = test(1)

那类装饰器该如何解决呢?

我现在还不知道该如何处理,如果有知道的朋友,请不吝赐教,十分感谢!!

5、多个装饰器的执行顺序总结

其实,我觉得不用特别的去记多个装饰器的执行顺序是如何的,我们最重要的是理解到装饰器的执行逻辑是如何的。函数装饰器和类装饰器的初始化顺序都是一样的:从靠近被装饰的函数开始执行初始化操作。把这个核心原理理解到后,多个装饰器的执行顺序在使用的时候,就很容易得到了。

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

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

相关文章

使用JProfiler进入JVM分析

要评测JVM,必须将JProfiler的评测代理加载到JVM中。这可以通过两种不同的方式发生:在启动脚本中指定-agentpath VM参数,或者使用attach API将代理加载到已经运行的JVM中。 JProfiler支持这两种模式。添加VM参数是评测的首选方式,集…

拥抱创新:用Kotlin开发高效Android应用

拥抱创新:用Kotlin开发高效Android应用 引言 在当今数字时代,移动应用已经成为人们生活中不可或缺的一部分。无论是社交媒体、电子商务还是健康管理,移动应用已经深刻地影响了我们的生活方式。随着移动设备的普及和功能的增强,A…

【JAVA】类和对象

作者主页:paper jie的博客 本文作者:大家好,我是paper jie,感谢你阅读本文,欢迎一建三连哦。 本文录入于《JAVASE语法系列》专栏,本专栏是针对于大学生,编程小白精心打造的。笔者用重金(时间和精…

高项V4.高级PM.项目集set+项目组合portfolio+组织级OPM+量化项目管理+实践模型

PMI , ITSS 、CMMI 和PRINCE2 等为各类信息系统项目管理提供了最佳实践,井提供了对组织的项目管理能力进行持续改进和评估的方法。 第一部分 项目集--《项目集管理标准>> (第4 版) ---实现项目11>2的更大效益 由项目管理协会(PMI) 出版的《…

OpenCV之信用卡识别实战

文章目录 代码视频讲解模板匹配文件主程序(ocr_template_match.py)myutils.py 代码 链接: https://pan.baidu.com/s/1KjdiqkyYGfHk97wwgF-j3g?pwdhhkf 提取码: hhkf 视频讲解 模板匹配文件 主程序(ocr_template_match.py) # 导入工具包 from imutils import contours # 从…

算术逻辑单元(ALU)(数电、加法器)

优先级:与>或 异或电路 依旧需要一级级的传递,后算完才能前传

[oeasy]python0079_控制序列_光标位置设置_ESC_逃逸字符_CSI

光标位置 回忆上次内容 上次我们研究的比较杂 类型转化进制转化捕获异常版本控制生成帮助文档变量的常用类型变量的生命周期控制 数据类型主要研究了两个 字符串 str 整型数字 int 字符串型 和 整型数字型变量 是可以相互转化的 加法运算逻辑 会根据操作变量的不同 而不同…

针对java程序员的了解细节操作系统与进程

一、💛 操作系统(浅浅概念):是用来搞管理软件的 1.对下,要管理各种硬件设备 2.对上,要给应用程序提供一个稳定的运行环境 二、💙 进程:正在运行的程序,假如程序没有运行就不叫程序,…

如何在终端设置代理(设置jupyter notebook同理)

设置代理 在终端(我用的gitbash)下执行 set HTTP_PROXYhttp://<user>:<password><proxy server>:<proxy port> set HTTPS_PROXYhttp://<user>:<password><proxy server>:<proxy port>其中&#xff1a; user、password&#…

LabVIEW开发3D颈动脉图像边缘检测

LabVIEW开发3D颈动脉图像边缘检测 近年来&#xff0c;超声图像在医学领域对疾病诊断具有重要意义。边缘检测是图像处理技术的重要组成部分。边缘包含图像信息。边缘检测的主要目的是根据强度和纹理等属性识别图像中均匀区域的边界。超声&#xff08;US&#xff09;图像存在视觉…

SpringMVC视图

SpringMVC视图 视图的作用是渲染数据&#xff0c;将模型Model中的数据展示给客户&#xff0c;SpringMVC中视图的种类有很多&#xff0c;默认有转发视图(InternalResourceView)和重定向视图(RedirectView)。 当工程引入jstl的依赖&#xff0c;转发视图会自动跳转jstlView,若使用…

11.物联网操作系统内存管理

一。STM32编译过程及程序组成 STM32编译过程 程序的组成、存储与运行 MDK生成的主要文件分析 1.STM32编译过程 1.源文件&#xff08;Source code&#xff09;--》目标文件&#xff08;Object code&#xff09; .c(C语言)通过armcc生成.o&#xff0c;.s&#xff08;汇编&…

附件展示 点击下载

效果图 实现代码 <el-table-column prop"attachment" label"合同附件" width"250" show-overflow-tooltip><template slot-scope"scope"><div v-if"scope.row.cceedcAppendixInfoList &&scope.row.ccee…

背包问题详解(动态规划):01背包、完全背包、多重背包

动态规划&#xff1a; 基本思想&#xff1a; 动态规划算法通常用于求解具有某种最优性质的问题。在这类问题中&#xff0c; 可能会有很多可行解。没一个解都对应于一个值&#xff0c;我们希望找到具有最优值的解。胎动规划算法与分治法类似&#xff0c;其基本思想也是将待求解…

SpringBoot使用@Autowired将实现类注入到List或者Map集合中

前言 最近看到RuoYi-Vue-Plus翻译功能 Translation的翻译模块配置类TranslationConfig&#xff0c;其中有一个注入TranslationInterface翻译接口实现类的写法让我感到很新颖&#xff0c;但这种写法在Spring 3.0版本以后就已经支持注入List和Map&#xff0c;平时都没有注意到这…

Docker从零到掌握(详解)

目录 1.初识Docker 1.1 为什么使用docker 1.2 Docker技术 1.3.安装Docker 1.4.Docker架构 1.5.配置Docker镜像加速器 2.Docker常用命令 2.1.Docker服务相关的命令 2.2.Docker镜像相关的命令 2.3.Docker容器相关的命令 3. 容器的数据卷 3.1.数据卷的概念和作用 3.2…

Django架构图

1. Django 简介 基本介绍 Django 是一个由 Python 编写的一个开放源代码的 Web 应用框架 使用 Django&#xff0c;只要很少的代码&#xff0c;Python 的程序开发人员就可以轻松地完成一个正式网站所需要的大部分内容&#xff0c;并进一步开发出全功能的 Web 服务 Django 本身…

【Shell】基础语法(一)

文章目录 一、shell的介绍二、执行脚本三、shell的基本语法1. 变量的使用2. 变量的分类 一、shell的介绍 Shell的作用是解释执行用户的命令&#xff0c;用户输入一条命令&#xff0c;Shell就解释执行一条&#xff0c;这种方式称为交互式&#xff08;Interactive&#xff09;&a…

刷了3个月的华为OD算法题,总结了270多道,谈谈自己的感悟

目录 一、考研二战&#xff0c;入职华为&#xff0c;反向调剂电子科大深圳二、题目描述三、输入描述四、输出描述五、解题思路六、Java算法源码七、效果展示1、输入2、输出3、说明 大家好&#xff0c;我是哪吒。 最近一直在刷华为OD机试的算法题&#xff0c;坚持一天三道题的节…

计算机网络(6) --- https协议

计算机网络&#xff08;5&#xff09; --- http协议_哈里沃克的博客-CSDN博客http协议https://blog.csdn.net/m0_63488627/article/details/132089130?spm1001.2014.3001.5501 目录 1.HTTPS的出现 1.HTTPS协议介绍 2.补充概念 1.加密 1.解释 2.原因 3.加密方式 对称加…