内容简介:这篇文章主要介绍了Python多层装饰器用法,结合实例形式简单分析了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多层装饰器用法实例分析》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Probability and Computing
Michael Mitzenmacher、Eli Upfal / Cambridge University Press / 2005-01-31 / USD 66.00
Assuming only an elementary background in discrete mathematics, this textbook is an excellent introduction to the probabilistic techniques and paradigms used in the development of probabilistic algori......一起来看看 《Probability and Computing》 这本书的介绍吧!