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
![]() | 1 shaodamao OP 有没有大佬帮忙看一下 |
2 lolizeppelin 2017-08-19 20:14:04 +08:00 via Android ![]() 装饰器是单纯的套娃语法糖 具体看套的是什么 有的是闭包 有的是描述器 上面那个是闭包 套一层只能传不带参数的函数 套二层能传函数参数 套三层能传入预参数 |
3 lolizeppelin 2017-08-19 20:23:08 +08:00 via Android 顺便说下 。上面那种写法用得少一点 属于先套函数参数再套函数的 一般写法是先套 fun |
![]() | 4 shaodamao OP @lolizeppelin 谢谢大佬,昨晚在一哥们指导下已经看明白了,今天一看大佬回复,更加深了理解。么么哒 |