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程序设计有所帮助。