Python 多层装饰器

xiaoxiao2021-02-27  116

前言

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 装饰的是一个函数,而不是一个装饰器。

转载请注明原文地址: https://www.6miu.com/read-15989.html

最新回复(0)