我有一个关于装饰器的问题。我了解什么是装饰器,我知道如何使用它,我已经阅读了所有本教程 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)
在这点上是一样的:
>>> def my_decorator(fn):
>>> print 'Do something before'
>>> print fn()
>>> @my_decorator
>>> def foo():
>>> return 'Hello World!'
我知道什么是闭包以及为什么我们在带参数的装饰器中使用闭包(以获取嵌套函数中的装饰器参数)但我不明白的是为什么我们使用闭包和嵌套函数来获取参数和函数。
闭包(或其他东西)如何访问参数和外部函数。没有@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)
这怎么可能?
请您参考如下方法:
我找到了解决方案:
事实上,装饰器使用闭包功能: 所以这里是不带装饰器带参数做同样事情的解决方案(只是了解操作,学习)
def wrapper(str):
def decorator_factory(fn):
def inner_function(*args):
print 'Do something before'
return fn(*args)
return inner_function
return decorator_factory
@my_decorator('test')
def foo(a, b):
return a + b
# with decorator
print foo(1, 1)
# without decorator
print wrapper('str')(foo)(1, 1)
