如何制作函数装饰器并将它们链接在一起? [英] How to make function decorators and chain them together?

查看:33
本文介绍了如何制作函数装饰器并将它们链接在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中创建两个装饰器来执行以下操作?

How can I make two decorators in Python that would do the following?

@makebold
@makeitalic
def say():
   return "Hello"

...应该返回:

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

我并不是要在实际应用程序中以这种方式制作 HTML - 只是想了解装饰器和装饰器链的工作原理.

I'm not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works.

推荐答案

查看文档 看看装饰器是如何工作的.这是您的要求:

Check out the documentation to see how decorators work. Here is what you asked for:

from functools import wraps

def makebold(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return "<b>" + fn(*args, **kwargs) + "</b>"
    return wrapper

def makeitalic(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return "<i>" + fn(*args, **kwargs) + "</i>"
    return wrapper

@makebold
@makeitalic
def hello():
    return "hello world"

@makebold
@makeitalic
def log(s):
    return s

print hello()        # returns "<b><i>hello world</i></b>"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello')   # returns "<b><i>hello</i></b>"

这篇关于如何制作函数装饰器并将它们链接在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆