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

yipeiwu_com6年前Python基础

本文实例讲述了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相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

Python中的zipfile模块使用详解

zip文件格式是通用的文档压缩标准,在ziplib模块中,使用ZipFile类来操作zip文件,下面具体介绍一下: class zipfile.ZipFile(file[, mode[,...

利用python实现PSO算法优化二元函数

利用python实现PSO算法优化二元函数

python实现PSO算法优化二元函数,具体代码如下所示: import numpy as np import random import matplotlib.pyplot a...

Python多线程编程(四):使用Lock互斥锁

前面已经演示了Python:使用threading模块实现多线程编程二两种方式起线程和Python:使用threading模块实现多线程编程三threading.Thread类的重要函数...

python3 批量获取对应端口服务的实例

思路懒得写了. 依赖python-nmap,先在电脑上装nmap,不然用不了.openpyxl实际上没有用到,可以不安装. makeEx()没用到,懒得删了. #依赖python-n...

Python实现的json文件读取及中文乱码显示问题解决方法

本文实例讲述了Python实现的json文件读取及中文乱码显示问题解决方法。分享给大家供大家参考,具体如下: city.json文件的内容如下: { "cities": [ {...