Python多层装饰器用法实例分析

作者:路虽远在路上 时间:2023-08-20 07:34:35 

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

前言

Python 的装饰器能够在不破坏函数原本结构的基础上,对函数的功能进行补充。当我们需要对一个函数补充不同的功能,可能需要用到多层的装饰器。在我的使用过程中,遇到了两种装饰器层叠的情况,这里把这两种情况写下来,作为踩坑记录。

情况1


def A(funC):
 def decorated_C(funE):
   def decorated_E_by_CA(*args, **kwargs):
     out = funC(funE)(*args, **kwargs)
     return out +' > decorated by A'
   return decorated_E_by_CA
 return decorated_C
@A
def C(funE):
 def decorated_E_by_C(str):
   return funE(str)+' > decorated by C'
 return decorated_E_by_C
@C
def E(str):
 return str
print E('A string is ')

这种情况下首先 E(str) = C(E)(str),然后由于C = A(C),还有 E(str) = A(C)(E)(str)。这么一来他们的关系就明确了,装饰器 A 装饰的是装饰器 C,它返回了一个被装饰过的装饰器,而被装饰过的装饰器又可以去装饰函数 E。在上面的代码中,decorated_C 就是一个被装饰过的装饰器。

情况2


def A(funE_decorated_by_C):
 def redecorated_E(str):
   return funE_decorated_by_C(str)+' > redecorated by A'
 return redecorated_E
def C(funE):
 def decorated_E(str):
   return funE(str)+' > decorated by C'
 return decorated_E
@A
@C
def E(str):
 return str
print E('A string is ')

这种情况下,有 E(str) = A(C(E))(str)。首先装饰器 C 装饰函数 E,返回一个被 C 装饰过的函数,然后装饰器 A 再装饰这个被 C 装饰过的函数。与第一种情况的区别是,这里的装饰器 A 装饰的是一个函数,而不是一个装饰器

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

来源:http://blog.csdn.net/u010185894/article/details/71191811

标签:Python,多层装饰器
0
投稿

猜你喜欢

  • 用正则表达式找出不包含连续字符串abc的单词

    2010-03-02 20:28:00
  • ASP:Cookie使用指南

    2007-09-28 12:48:00
  • python中根据字符串调用函数的实现方法

    2023-10-03 03:40:12
  • python得到一个excel的全部sheet标签值方法

    2022-11-22 15:27:51
  • TensorFlow2.1.0安装过程中setuptools、wrapt等相关错误指南

    2023-07-30 10:28:08
  • HTTP协议详细介绍

    2022-08-09 23:52:24
  • urllib和BeautifulSoup爬取维基百科的词条简单实例

    2023-10-25 21:46:59
  • 使用 MySQL Date/Time 类型

    2024-05-13 09:21:22
  • python密码学Vignere密码教程

    2022-12-06 10:21:22
  • Python中利用ItsDangerous快捷实现数据加密

    2022-06-09 23:24:41
  • Asp操作Xml的精炼类,含示例代码

    2011-02-28 11:11:00
  • 通过Python把学姐照片做成拼图游戏

    2022-03-24 17:21:01
  • Python实现网络聊天室的示例代码(支持多人聊天与私聊)

    2022-11-21 15:17:23
  • Python树莓派学习笔记之UDP传输视频帧操作详解

    2023-04-21 10:03:20
  • python面向对象 反射原理解析

    2021-05-14 08:56:32
  • python使用递归解决全排列数字示例

    2022-02-22 04:14:49
  • word-wrap同word-break的区别

    2007-10-24 20:08:00
  • asp中提取HTML中图片的SRC路径

    2008-10-24 08:42:00
  • OpenCV MediaPipe实现颜值打分功能

    2022-06-19 08:22:16
  • python time时间库详解

    2023-10-09 03:20:57
  • asp之家 网络编程 m.aspxhome.com