我如何在Python中制作两个装饰器来完成以下操作?

@make_bold
@make_italic
def say():
   return "Hello"

调用say()应返回:

"<b><i>Hello</i></b>"

当前回答

装饰只是语法上的糖。

This

@decorator
def func():
    ...

扩展到

def func():
    ...
func = decorator(func)

其他回答

说到计数器示例-如上所述,计数器将在使用decorator的所有函数之间共享:

def counter(func):
    def wrapped(*args, **kws):
        print 'Called #%i' % wrapped.count
        wrapped.count += 1
        return func(*args, **kws)
    wrapped.count = 0
    return wrapped

这样,您的装饰器可以重复用于不同的函数(或用于多次装饰同一个函数:func_counter1=counter(func);func_counter2=counter(func)),并且计数器变量将对每个变量保持私有。

或者,您可以编写一个工厂函数,该函数返回一个装饰器,该装饰器将装饰函数的返回值包装在传递给工厂函数的标记中。例如:

from functools import wraps

def wrap_in_tag(tag):
    def factory(func):
        @wraps(func)
        def decorator():
            return '<%(tag)s>%(rv)s</%(tag)s>' % (
                {'tag': tag, 'rv': func()})
        return decorator
    return factory

这使您能够编写:

@wrap_in_tag('b')
@wrap_in_tag('i')
def say():
    return 'hello'

or

makebold = wrap_in_tag('b')
makeitalic = wrap_in_tag('i')

@makebold
@makeitalic
def say():
    return 'hello'

就我个人而言,我会用不同的方式来编写装饰器:

from functools import wraps

def wrap_in_tag(tag):
    def factory(func):
        @wraps(func)
        def decorator(val):
            return func('<%(tag)s>%(val)s</%(tag)s>' %
                        {'tag': tag, 'val': val})
        return decorator
    return factory

这将产生:

@wrap_in_tag('b')
@wrap_in_tag('i')
def say(val):
    return val
say('hello')

不要忘了decorator语法是一种简写的构造:

say = wrap_in_tag('b')(wrap_in_tag('i')(say)))

当您需要在decorator中添加自定义参数时,我会添加一个案例,将其传递给最终函数,然后使用它。

装饰师:

def jwt_or_redirect(fn):
  @wraps(fn)
  def decorator(*args, **kwargs):
    ...
    return fn(*args, **kwargs)
  return decorator

def jwt_refresh(fn):
  @wraps(fn)
  def decorator(*args, **kwargs):
    ...
    new_kwargs = {'refreshed_jwt': 'xxxxx-xxxxxx'}
    new_kwargs.update(kwargs)
    return fn(*args, **new_kwargs)
  return decorator

以及最终功能:

@app.route('/')
@jwt_or_redirect
@jwt_refresh
def home_page(*args, **kwargs):
  return kwargs['refreched_jwt']

下面有make_bold()和make_italic():

def make_bold(func):
    def core(*args, **kwargs):
        result = func(*args, **kwargs)
        return "<b>" + result + "</b>"
    return core

def make_italic(func):
    def core(*args, **kwargs):
        result = func(*args, **kwargs)
        return "<i>" + result + "</i>"
    return core

您可以使用say()将它们用作装饰器,如下所示:

@make_bold
@make_italic
def say():
   return "Hello"

print(say())

输出:

<b><i>Hello</i></b>

当然,您可以直接使用make_bold()和make_italic()而不使用修饰符,如下所示:

def say():
    return "Hello"
    
f1 = make_italic(say)
f2 = make_bold(f1)
result = f2()
print(result)

简而言之:

def say():
    return "Hello"
    
result = make_bold(make_italic(say))()
print(result)

输出:

<b><i>Hello</i></b>

Paolo Bergan蒂诺的答案具有只使用stdlib的巨大优势,适用于这个简单的示例,其中既没有修饰器参数,也没有修饰函数参数。

然而,如果您想处理更一般的情况,它有三个主要限制:

正如在几个答案中已经指出的,您不能轻易地修改代码以添加可选的修饰符参数。例如,创建makestyle(style='bold')装饰器非常简单。此外,使用@functools.wraps创建的包装器不保留签名,因此如果提供了错误的参数,它们将开始执行,并且可能引发与通常的TypeError不同的错误。最后,在使用@functools.wraps创建的包装器中,很难根据其名称访问参数。事实上,参数可以出现在*args、**kwargs中,也可以根本不出现(如果是可选的)。

我写了decopatch来解决第一个问题,写了makefun.wraps来解决另外两个问题。注意,makefun利用了与著名的decorator lib相同的技巧。

这是如何创建带有参数的装饰器,返回真正的签名保护包装器:

from decopatch import function_decorator, DECORATED
from makefun import wraps

@function_decorator
def makestyle(st='b', fn=DECORATED):
    open_tag = "<%s>" % st
    close_tag = "</%s>" % st

    @wraps(fn)
    def wrapped(*args, **kwargs):
        return open_tag + fn(*args, **kwargs) + close_tag

    return wrapped

decopatch为您提供了其他两种开发样式,根据您的喜好,隐藏或显示各种python概念。最紧凑的样式如下:

from decopatch import function_decorator, WRAPPED, F_ARGS, F_KWARGS

@function_decorator
def makestyle(st='b', fn=WRAPPED, f_args=F_ARGS, f_kwargs=F_KWARGS):
    open_tag = "<%s>" % st
    close_tag = "</%s>" % st
    return open_tag + fn(*f_args, **f_kwargs) + close_tag

在这两种情况下,您都可以检查装饰器是否按预期工作:

@makestyle
@makestyle('i')
def hello(who):
    return "hello %s" % who

assert hello('world') == '<b><i>hello world</i></b>'    

有关详细信息,请参阅文档。