Python装饰器

2024-04-24 06:55:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于装修工的问题。我知道什么是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)

这怎么可能?在


Tags: 函数decorators参数returnfoomydeffunction
2条回答

Decorator是一个接受一个参数的函数(这个参数是function)——这是Decorator的定义。在您的例子中,wrapper是decorator。而my_decorator用于收集inner_function的参数。inner_function用于替换原始的[not decorated]函数。逐步解释如下:

  1. ^调用{}来收集inner_function的选项
  2. my_decorator返回wrapper
  3. wrapper负责捕获原始函数,或者换句话说就是修饰它。在您的例子中,原始函数是foo。在
  4. wrapper返回原始的替换函数(即inner_function
  5. 从现在起,foo指向inner_function,因此执行inner_function,然后调用{}

希望能让事情更清楚一点。在

我找到了解决办法:

实际上,decorator使用闭包功能: 所以这里有一个解决方案,可以在没有decorator和参数的情况下做同样的事情(这只是为了理解操作,并学习)

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)

相关问题 更多 >