V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
nlimpid
V2EX  ›  Python

使用 functools.wraps 具体能解决哪些问题?

  •  
  •   nlimpid ·
    nlimpid · 2017-06-25 23:02:15 +08:00 · 2527 次点击
    这是一个创建于 2495 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看到 fluent python 第 7 章例 7-15 中写道:

    最开始实现的装饰器有几个缺点:不支持关键字参数,而且遮盖了被装饰函数的 namedoc 属性。

    之后用 functools.wraps 解决。函数自身的属性好理解,但是为什么新版能够正确处理关键字参数呢?

    附上前后两个装饰器代码 https://notepad.pw/code/c2cetz9um

    6 条回复    2017-06-28 13:07:55 +08:00
    wwqgtxx
        1
    wwqgtxx  
       2017-06-26 01:51:02 +08:00 via iPhone
    因为他本身的实现类似于
    def wraps(func):
    def _warps(_func):
    _func.__name__=func.__name__
    _func.__doc__=func.__doc__
    return _func
    return _warps
    wwqgtxx
        2
    wwqgtxx  
       2017-06-26 01:52:28 +08:00 via iPhone
    重新排版一下
    def wraps(func):
    ----def _warps(_func):
    --------_func.__name__=func.__name__
    --------_func.__doc__=func.__doc__
    --------return _func
    ----return _warps
    wwqgtxx
        3
    wwqgtxx  
       2017-06-26 01:58:33 +08:00 via iPhone
    至于“装饰器不支持关键词参数”,好奇具体是怎么个不支持法,请说明具体的不支持的写法
    nlimpid
        4
    nlimpid  
    OP
       2017-06-26 08:26:21 +08:00
    @wwqgtxx 我就是看原文是直接这么写的才问的。
    gulu
        5
    gulu  
       2017-06-26 20:00:45 +08:00 via Android
    楼主试试用 Pycharm 去 Ctrl + B 吧 😀
    kkzxak47
        6
    kkzxak47  
       2017-06-28 13:07:55 +08:00
    "Sadly most decorators are broken because the web is full of bad advice."
    https://hynek.me/articles/decorators/
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3470 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:18 · PVG 19:18 · LAX 04:18 · JFK 07:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.