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
shaodamao
V2EX  ›  Python

萌新求助,关于 Python 装饰器

  •  
  •   shaodamao · 2017-08-19 17:40:37 +08:00 · 1501 次点击
    这是一个创建于 2440 天前的主题,其中的信息可能已经有所发展或是发生改变。

    stackoverflow 中 How to make a chain of function decorators?( https://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators )中,最高票答案(目前为 3560 票)的“ Let ’ s practice: decorating a decorator ”部分第一个装饰器的具体作用是什么?请详细讲一下。

    该装饰器如下:

    ——————————————————————

    def decorator_with_args(decorator_to_enhance):

    # We use the same trick we did to pass arguments
    def decorator_maker(*args, **kwargs):
    
        # We create on the fly a decorator that accepts only a function
        # but keeps the passed arguments from the maker.
        def decorator_wrapper(func):
    
            # We return the result of the original decorator, which, after all, 
            # IS JUST AN ORDINARY FUNCTION (which returns a function).
            # Only pitfall: the decorator must have this specific signature or it won't work:
            return decorator_to_enhance(func, *args, **kwargs)
    
        return decorator_wrapper
    
    return decorator_maker
    
    shaodamao
        1
    shaodamao  
    OP
       2017-08-19 19:37:04 +08:00
    有没有大佬帮忙看一下
    lolizeppelin
        2
    lolizeppelin  
       2017-08-19 20:14:04 +08:00 via Android   ❤️ 1
    装饰器是单纯的套娃语法糖

    具体看套的是什么


    有的是闭包 有的是描述器


    上面那个是闭包

    套一层只能传不带参数的函数
    套二层能传函数参数
    套三层能传入预参数
    lolizeppelin
        3
    lolizeppelin  
       2017-08-19 20:23:08 +08:00 via Android
    顺便说下 。上面那种写法用得少一点 属于先套函数参数再套函数的


    一般写法是先套 fun
    shaodamao
        4
    shaodamao  
    OP
       2017-08-20 16:07:02 +08:00
    @lolizeppelin 谢谢大佬,昨晚在一哥们指导下已经看明白了,今天一看大佬回复,更加深了理解。么么哒
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1010 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 19:54 · PVG 03:54 · LAX 12:54 · JFK 15:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.