如何创建一个函数装饰器链?

weixin_38057949 2019-09-12 11:32:54
如何在Python中创建两个装饰器来执行以下操作? @makebold @makeitalic def say(): return "Hello" …应该返回: "<b><i>Hello</i></b>" 我不是试图在实际应用程序中以这种方式制作HTML – 只是想了解装饰器和装饰器链是如何工作的.
...全文
30 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38062738 2019-09-12
  • 打赏
  • 举报
回复
查看the documentation以了解装饰器的工作原理.这是你要求的: from functools import wraps def makebold(fn): @wraps(fn) def wrapped(*args, **kwargs): return "<b>" + fn(*args, **kwargs) + "</b>" return wrapped def makeitalic(fn): @wraps(fn) def wrapped(*args, **kwargs): return "<i>" + fn(*args, **kwargs) + "</i>" return wrapped @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>"

476

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧