将装饰器列表应用于可调用对象? [英] Apply a list of decorators to a callable?
问题描述
给出装饰器方法列表,如何将这些方法应用于可调用方法?
Given a list of decorator methods, how would one apply those to a callable?
例如,由于:
@foo
@bar
def baz():
pass
...是等同于:
def baz():
pass
baz = foo(bar(baz)))
...人们会以为带有装饰器列表( [ foo,bar]
)可以将它们动态地应用于 baz
。
...one would assume that with a list of decorators ([foo, bar]
) they could be applied to baz
dynamically.
推荐答案
还有另一个装饰器!
def yad(decorators):
def decorator(f):
for d in reversed(decorators):
f = d(f)
return f
return decorator
示例用法
list_of_decorators = [foo, bar]
@yad(list_of_decorators)
def foo():
print 'foo'
没有装饰器语法,看起来像是
Without the decorator syntax, it would look like
func = yad(list_of_decorators)(func)
如果您要将同一列表应用于多个功能,则可以执行以下操作:
If you wanted to apply the same list to multiple functions, you can do it like:
dec = yad(list_of_decorators)
func1 = dec(func1)
@dec
def func2():
pass
这些注释,您可以定义 yad
(我敢肯定有一个更好的名字)来接受 * decorators
装饰器
。然后,如果要在原位创建列表 ,则不必使用方括号。如果列表是在其他地方创建的,那么我演示的方法会更好。
As recursive points out in the comments, you can define yad
(I'm sure there's a better name for this) to accept *decorators
instead of decorators
. Then you don't have to use brackets if you're creating the list in situ. The way that I've demonstrated is better if the list is created elsewhere.
这篇关于将装饰器列表应用于可调用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!