翼度科技»论坛 编程开发 python 查看内容

谈一谈Python中的装饰器

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
1、装饰器基础介绍

1.1 何为Python中的装饰器?

Python中装饰器的定义以及用途:
装饰器是一种特殊的函数,它可以接受一个函数作为参数,并返回一个新的函数。装饰器可以用来修改或增强函数的行为,而不需要修改函数本身的代码。在Python中,装饰器通常用于实现AOP(面向切面编程),例如日志记录、性能分析、缓存等。装饰器的语法使用@符号,将装饰器函数放在被装饰函数的定义之前
学过设计模式的朋友都知道,设计模式的结构型模式中也有一个叫装饰器模式,那这个和Python中的装饰器有什么不同呢?
设计模式中的装饰器的定义以及用途:
设计模式中的装饰器是一种结构型模式,它可以在不改变原对象的情况下,为对象添加额外的功能。装饰器模式通常用于在运行时动态地为对象添加功能,而不是在编译时静态地为对象添加功能。装饰器模式通常涉及到多个对象之间的协作,而不是单个函数或对象。
因此,Python中的装饰器和设计模式中的装饰器虽然名称相同,但是它们的实现方式和应用场景有很大的不同。
1.2 闭包

那Python种的装饰器是怎么实现的呢?先不用着急,我们先来一起学习学习Python中的闭包。
那什么叫做闭包呢?
闭包是指一个函数和它所在的环境变量的组合,即在函数内部定义的函数可以访问外部函数的变量和参数,即使外部函数已经返回。闭包可以用来实现函数式编程中的柯里化、惰性求值、函数组合等高级特性。
看着上面的文字,是不是感觉有点抽象。我说一说我对闭包的理解
闭包是由外部函数和内部函数,内部函数引用到了外部函数定义的变量,外部函数的返回值是内部函数的函数名。对于这样的函数,我们就称为闭包。
好像也有点抽象,我们来看一断代码,就能够理解上面的话了。
  1. def my_decorator():  # my_decorator 这个就叫做外部函数
  2.     a = 1
  3.     def inner():  # inner 这个叫做内部函数
  4.         print(a)  # 内部函数引用到了外部函数中定义的变量
  5.     return inner  # 外部函数的返回值是内部函数名
复制代码
2、函数装饰器的实现

上面讲解了装饰器的定义、用途,还有闭包,那怎么去实现一个装饰器呢?不急,接下来我们一起来学习如何实现装饰器。
装饰器不是说可以不改变一个函数源代码的基础上,给这个函数添加额外的功能吗?那怎么做呢?
接下来,我们就一起实现一个装饰器,来计算函数的执行时间。Let‘s go!
2.1 不使用@实现装饰器

首先,使用闭包定义一个统计函数执行时间的功能。
  1. def process_time(func):
  2.     def inner(*args, **kwargs):
  3.         start_time = time.time()
  4.         ret = func(*args, **kwargs)
  5.         end_time = time.time()
  6.         print("函数的执行时间为:%d" % (end_time-start_time))
  7.         return ret
  8.     return inner
复制代码
接下来定义一个函数,使用比较来计算函数的执行时间。
  1. import timedef process_time(func):
  2.     def inner(*args, **kwargs):
  3.         start_time = time.time()
  4.         ret = func(*args, **kwargs)
  5.         end_time = time.time()
  6.         print("函数的执行时间为:%d" % (end_time-start_time))
  7.         return ret
  8.     return innerdef test(sleep_time):    time.sleep(sleep_time)t1 = process_time(test)t1(1)print("------------")t1(2)
复制代码
执行结果:
  1. 函数的执行时间为:1
  2. ------------
  3. 函数的执行时间为:2
复制代码
通过上面的代码,我们观察到,我们并没有修改test函数的源代码,依旧给test函数添加上了统计函数执行时间的功能。
Python中实现上述功能,有更加优雅的方式。下面,我们就一起来看看如何实现的。
2.2 Python中使用语法糖的装饰器(推荐使用)
  1. import timedef process_time(func):
  2.     def inner(*args, **kwargs):
  3.         start_time = time.time()
  4.         ret = func(*args, **kwargs)
  5.         end_time = time.time()
  6.         print("函数的执行时间为:%d" % (end_time-start_time))
  7.         return ret
  8.     return inner@process_timedef test(sleep_time):    time.sleep(sleep_time)test(1)print("------------")test(2)
复制代码
执行结果:
  1. 函数的执行时间为:1
  2. ------------
  3. 函数的执行时间为:2
复制代码
观察上面的代码变动,发现只有很少的部分修改了。
1、test函数上面添加了一行@process_time。
2、test函数的调用方式发生了改变。
其他的并没有发生变化,整个代码看起来也更加清爽了。
提示:
当使用@装饰器时,会自动执行 闭包中的外部函数内容。这个可以自行验证。
当使用@装饰器时,Python解释器为我们做了什么?
当使用@装饰器时,Python解释器会将被装饰的函数作为参数传递给装饰器函数,并将其返回值作为新的函数对象替换原来的函数对象。这样,每次调用被装饰的函数时,实际上是调用了装饰器函数返回的新函数对象。
Python 装饰器 @ 实际上是一种语法糖,它可以让我们在不改变原函数代码的情况下,对函数进行扩展或修改。当我们使用 @ 装饰器时,实际上是将被装饰函数作为参数传递给装饰器函数,然后将装饰器函数的返回值赋值给原函数名。因此,@ 装饰器并不会进行内存拷贝。
通过下面的函数,可以得知,inner和test函数指向的是同一个内存地址。
  1. import time
  2. def process_time(func):
  3.     print("func id --->", id(func))
  4.     def inner(*args, **kwargs):
  5.         start_time = time.time()
  6.         ret = func(*args, **kwargs)
  7.         end_time = time.time()
  8.         print("函数的执行时间为:%d" % (end_time - start_time))
  9.         return ret
  10.     print("inner id --->", id(inner))
  11.     return inner
  12. @process_time
  13. def test(sleep_time):
  14.     print("test func id --->", id(test))
  15.     time.sleep(sleep_time)
  16. print("test id --->", id(test))
复制代码
执行结果:
  1. func id ---> 4312377952
  2. inner id ---> 4313983008
  3. test id ---> 4313983008
复制代码
使用语法糖时,Python解释器底层为我们做了这样的处理。

2.3 多个装饰器的执行顺序

上面的两个例子,都只有一个装饰器,是不是Python只能写一个装饰器呢。其实不是的。主要是为了讲解简单。接下来,我们一起来看看,多个装饰器的执行顺序。
  1. def outer_1(func):
  2.     print("coming outer_1")
  3.     def inner_1():
  4.         print("coming inner_1")
  5.         func()
  6.     return inner_1
  7. def outer_2(func):
  8.     print("coming outer_2")
  9.     def inner_2():
  10.         print("coming inner_2")
  11.         func()
  12.     return inner_2
  13. def outer_3(func):
  14.     print("coming outer_3")
  15.     def inner_3():
  16.         print("coming inner_3")
  17.         func()
  18.     return inner_3
  19. @outer_1
  20. @outer_2
  21. @outer_3
  22. def test():
  23.     print("coming test")
  24. test()
复制代码
执行结果:
  1. coming outer_3
  2. coming outer_2
  3. coming outer_1
  4. coming inner_1
  5. coming inner_2
  6. coming inner_3
  7. coming test
复制代码
outer_3 -> outer_2 -> outer_1 -> inner_1 -> inner_2 -> inner_3 -> 被装饰函数

从上面的执行结果,可以得出如下结论:
  1. 使用多个装饰器装饰函数时,
  2. 外部函数的执行顺序是从下到上的。
  3. 内部函数的执行顺序是从下往上的。
复制代码
多个装饰器装饰函数时,Python解释器底层做了啥

通过下面这段代码验证
  1. def outer_1(func):
  2.     print("coming outer_1, func id -->", id(func))
  3.     def inner_1():
  4.         print("coming inner_1")
  5.         func()
  6.     print("inner_1 id -->", id(inner_1))
  7.     return inner_1
  8. def outer_2(func):
  9.     print("coming outer_2, func id -->", id(func))
  10.     def inner_2():
  11.         print("coming inner_2")
  12.         func()
  13.     print("inner_2 id -->", id(inner_2))
  14.     return inner_2
  15. def outer_3(func):
  16.     print("coming outer_3, func id -->", id(func))
  17.     def inner_3():
  18.         print("coming inner_3")
  19.         func()
  20.     print("inner_3 id -->", id(inner_3))
  21.     return inner_3
  22. @outer_1
  23. @outer_2
  24. @outer_3
  25. def test():
  26.     print("coming test")
  27. test()
复制代码
执行结果:
  1. coming outer_3, func id --> 4389102784
  2. inner_3 id --> 4389102928
  3. coming outer_2, func id --> 4389102928
  4. inner_2 id --> 4389103072
  5. coming outer_1, func id --> 4389103072
  6. inner_1 id --> 4389103216
  7. coming inner_1
  8. coming inner_2
  9. coming inner_3
  10. coming test
复制代码
2.4 带参数的装饰器

该如何实现带参数的装饰器呢,其实原理一样的,我们再定义一个外层函数,外层函数的返回值是内存函数的名称,即引用。
下面我们来看一个例子:
  1. def is_process(flag):
  2.     def outer_1(func):
  3.         print("coming outer_1, func id -->", id(func))
  4.         def inner_1():
  5.             print("coming inner_1")
  6.             if flag:
  7.                 func()
  8.         print("inner_1 id -->", id(inner_1))
  9.         return inner_1
  10.     return outer_1
  11. @is_process(True)
  12. def test():
  13.     print("coming test")
  14. test()
复制代码
注意:

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

猜一猜下面函数会输出什么?
  1. def outer_1(func):
  2.     def inner_1():
  3.         print("inner_1, func __name__", func.__name__)
  4.         print("inner_1, func __doc__", func.__doc__)
  5.         func()
  6.     return inner_1
  7. @outer_1
  8. def test():
  9.     """this is test"""
  10.     print("outer_1, func __name__", test.__name__)
  11.     print("outer_1, func __doc__", test.__doc__)
  12. test()
复制代码
函数执行结果:
  1. inner_1, func __name__ test
  2. inner_1, func __doc__ this is test
  3. test, test __name__ inner_1
  4. test, test __doc__ None
复制代码
注意到没,在test函数体内打印函数的 __name__、__doc__ 属性,居然变成内部函数的了。
这个是为什么呢?
Python装饰器在装饰函数时,会将原函数的函数名、文档字符串、参数列表等属性复制到装饰器函数中,但是装饰器函数并不会复制原函数的所有属性。例如,原函数的name属性、doc属性、module属性等都不会被复制到装饰器函数中。
为了避免这种情况,可以使用functools库中的wraps装饰器来保留原来函数对象的属性。wraps装饰器可以将原来函数对象的属性复制到新的函数对象中,从而避免属性丢失的问题。
  1. from functools import wraps
  2. def outer_1(func):
  3.     @wraps(func)
  4.     def inner_1():
  5.         print("inner_1, func __name__", func.__name__)
  6.         print("inner_1, func __doc__", func.__doc__)
  7.         func()
  8.     return inner_1
  9. @outer_1
  10. def test():
  11.     """this is test"""
  12.     print("test, test __name__", test.__name__)
  13.     print("test, test __doc__", test.__doc__)
  14. test()
复制代码
执行结果:
  1. inner_1, func __name__ test
  2. inner_1, func __doc__ this is test
  3. test, test __name__ test
  4. test, test __doc__ this is test
复制代码
4、类装饰器

上面我们都是使用的函数来实现装饰器的功能,那可不可以用类来实现装饰器的功能呢?我们知道函数实现装饰器的原理是外部函数的参数是被装饰的函数,外部函数返回内部函数的名称。内部函数中去执行被装饰的函数。
那么其实类也是可以用来实现装饰器的,因为当我们为 类 定义了 __call__方法时,这个类就成了可调用对象,实例化后可直接调用。
  1. class ProcessTime:
  2.     def __call__(self, *args, **kwargs):
  3.         print("call")
  4. p = ProcessTime()
  5. p()
复制代码
4.1 类装饰器的实现
  1. import time
  2. class ProcessTime:
  3.     def __init__(self, func):
  4.         print("coming ProcessTime __init__")
  5.         self.func = func
  6.     def __call__(self, *args, **kwargs):
  7.         start_time = time.time()
  8.         print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
  9.         ret = self.func(*args, **kwargs)
  10.         end_time = time.time()
  11.         print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
  12.         return ret
  13. @ProcessTime
  14. def test(sleep_time):
  15.     time.sleep(sleep_time)
  16.     return "tet"
  17. test(1)
复制代码
执行结果:
  1. coming ProcessTime __init__
  2. coming ProcessTime __call__, id(self.func) --> 4488922160
  3. ProcessTime 函数的执行时间为:1
复制代码
通过上面的执行结果,我们可以得到,@ProcessTime的作用是 test = ProcessTime(test)。又因为 ProcessTime定义了__call__方法,是可调用对象,所以可以像函数那样直接调用实例化ProcessTime后的对象。
这里可以验证,通过注释掉装饰器,手动初始化ProcessTime类。得到的结果是一样的。
  1. # @ProcessTime
  2. def test(sleep_time):
  3.     time.sleep(sleep_time)
  4.     return "tet"
  5. test = ProcessTime(test)
  6. test(1)
复制代码
4.2 多个类装饰器的执行顺序

多个类装饰器的执行顺序是怎么样的呢,这里我们也通过代码来进行验证。
  1. import time
  2. class ProcessTime:
  3.     def __init__(self, func):
  4.         print("coming ProcessTime __init__", id(self))
  5.         self.func = func
  6.     def __call__(self, *args, **kwargs):
  7.         start_time = time.time()
  8.         print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
  9.         ret = self.func(*args, **kwargs)
  10.         end_time = time.time()
  11.         print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
  12.         return ret
  13. class ProcessTime2:
  14.     def __init__(self, func):
  15.         print("coming ProcessTime2 __init__", id(self))
  16.         self.func = func
  17.     def __call__(self, *args, **kwargs):
  18.         start_time = time.time()
  19.         print("coming ProcessTime2 __call__, id(self.func) -->", id(self.func))
  20.         ret = self.func(*args, **kwargs)
  21.         end_time = time.time()
  22.         print("ProcessTime2 函数的执行时间为:%d" % (end_time - start_time))
  23.         return ret
  24. @ProcessTime
  25. @ProcessTime2
  26. def test(sleep_time):
  27.     time.sleep(sleep_time)
  28.     return "tet"
  29. # test = ProcessTime2(test)
  30. # test = ProcessTime(test)
  31. t = test(1)
复制代码
执行结果:
  1. coming ProcessTime2 __init__ 4472235104
  2. coming ProcessTime __init__ 4473162672
  3. coming ProcessTime __call__, id(self.func) --> 4472235104
  4. coming ProcessTime2 __call__, id(self.func) --> 4471735344
  5. ProcessTime2 函数的执行时间为:1
  6. ProcessTime 函数的执行时间为:1
复制代码
从上面的结果,我们得到,执行顺序是:
ProcessTime2 中的__init__ -> ProcessTime 中的__init__ -> ProcessTime 中的__call__ -> ProcessTime2 中的__call__
特别注意:
ProcessTime 中的__call__ 中的代码并不会执行完后再去执行 ProcessTime2 中的__call__,而是在调用 ret = self.func(*args, **kwargs) 方法后,就回去执行 ProcessTime2 中的__call__的代码。
4.3 类装饰器存在的问题

其实,类装饰器也存在和函数装饰器一样的问题。它会覆盖原函数的元数据信息,例如函数名、文档字符串、参数列表等。这可能会导致一些问题,例如调试时无法正确显示函数名、文档生成工具无法正确生成文档等。
  1. import time
  2. from functools import wraps
  3. class ProcessTime:
  4.     def __init__(self, func):
  5.         print("coming ProcessTime __init__", id(self))
  6.         self.func = func
  7.     def __call__(self, *args, **kwargs):
  8.         start_time = time.time()
  9.         print("coming ProcessTime __call__, id(self.func) -->", id(self.func))
  10.         ret = self.func(*args, **kwargs)
  11.         end_time = time.time()
  12.         print("ProcessTime 函数的执行时间为:%d" % (end_time - start_time))
  13.         return ret
  14.         
  15. @ProcessTime
  16. def test(sleep_time):
  17.     "tets"
  18.     print("test.__doc__", test.__doc__)
  19.     # print(test.__name__)  --> 报错,AttributeError: 'ProcessTime' object has no attribute '__name__'
  20.     time.sleep(sleep_time)
  21.     return "tet"
  22.   
  23. t = test(1)
复制代码
那类装饰器该如何解决呢?
我现在还不知道该如何处理,如果有知道的朋友,请不吝赐教,十分感谢!!
5、多个装饰器的执行顺序总结

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


来源:https://www.cnblogs.com/huageyiyangdewo/p/17322678.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具