我有一个关于装修工的问题。我知道什么是decorators,我知道如何使用它,我已经阅读了所有这篇教程How to make a chain of function decorators?
我明白:
>>> def my_decorator(fn):
>>> print 'Do something before'
>>> print fn()
>>> def foo():
>>> return 'Hello World!'
>>> foo = my_decorator(foo)
是一样的:
^{pr2}$我知道什么是闭包,为什么在带参数的decorator中使用闭包(在嵌套函数中获取decorator参数),但我不明白为什么我们使用闭包和嵌套函数来获取参数和函数。在
或者其他函数如何访问外部的参数。没有@decorator我也做不到。在
例如,我可以访问我的foo()和函数的参数,而无需在参数中传递此函数:
def my_decorator(str):
def wrapper(fn):
def inner_function(*args):
print 'Do something before'
return fn(*args)
return inner_function
return wrapper
@my_decorator('test')
def foo(a, b):
return a + b
print foo(1, 1)
这怎么可能?在
Decorator是一个接受一个参数的函数(这个参数是function)——这是Decorator的定义。在您的例子中,
wrapper
是decorator。而my_decorator
用于收集inner_function
的参数。inner_function
用于替换原始的[not decorated]函数。逐步解释如下:inner_function
的选项my_decorator
返回wrapper
wrapper
负责捕获原始函数,或者换句话说就是修饰它。在您的例子中,原始函数是foo
。在wrapper
返回原始的替换函数(即inner_function
)foo
指向inner_function
,因此执行inner_function
,然后调用{希望能让事情更清楚一点。在
我找到了解决办法:
实际上,decorator使用闭包功能: 所以这里有一个解决方案,可以在没有decorator和参数的情况下做同样的事情(这只是为了理解操作,并学习)
相关问题 更多 >
编程相关推荐