我可以在Python中将两个装饰器组合为一个吗? [英] Can I combine two decorators into a single one in Python?
本文介绍了我可以在Python中将两个装饰器组合为一个吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在Python中将两个装饰器组合成一个新的装饰器?
Is there a way to combine two decorators into one new decorator in python?
我意识到我可以将多个装饰器应用于一个函数,但是我很好奇
I realize I can just apply multiple decorators to a function, but I was curious as to whether there's some simple way to combine two into a new one.
推荐答案
更通用一些:
def composed(*decs):
def deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
然后
@composed(dec1, dec2)
def some(f):
pass
等同于
@dec1
@dec2
def some(f):
pass
这篇关于我可以在Python中将两个装饰器组合为一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文