萌新求助,关于 Python 装饰器

2017-08-19 17:40:37 +08:00
 shaodamao

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
1513 次点击
所在节点    Python
4 条回复
shaodamao
2017-08-19 19:37:04 +08:00
有没有大佬帮忙看一下
lolizeppelin
2017-08-19 20:14:04 +08:00
装饰器是单纯的套娃语法糖

具体看套的是什么


有的是闭包 有的是描述器


上面那个是闭包

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


一般写法是先套 fun
shaodamao
2017-08-20 16:07:02 +08:00
@lolizeppelin 谢谢大佬,昨晚在一哥们指导下已经看明白了,今天一看大佬回复,更加深了理解。么么哒

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/384211

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX