V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Aug 19, 2017 · 2271 views
    This topic created in 3176 days ago, the information mentioned may be changed or developed.

    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
       Aug 19, 2017
    有没有大佬帮忙看一下
    lolizeppelin
        2
    lolizeppelin  
       Aug 19, 2017 via Android   ❤️ 1
    装饰器是单纯的套娃语法糖

    具体看套的是什么


    有的是闭包 有的是描述器


    上面那个是闭包

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


    一般写法是先套 fun
    shaodamao
        4
    shaodamao  
    OP
       Aug 20, 2017
    @lolizeppelin 谢谢大佬,昨晚在一哥们指导下已经看明白了,今天一看大佬回复,更加深了理解。么么哒
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   797 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 20:32 · PVG 04:32 · LAX 13:32 · JFK 16:32
    ♥ Do have faith in what you're doing.