且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python中将参数传递给装饰器

更新时间:2022-02-04 00:55:12

装饰器是返回函数的函数.当将参数传递给装饰器"时,您实际上所做的是调用一个返回装饰器的函数.因此decAny()应该是一个返回一个函数的函数,该函数返回一个函数.

Decorators are functions that return functions. When "passing a parameter to the decorator" what you are actually doing is calling a function that returns a decorator. So decAny() should be a function that returns a function that returns a function.

它看起来像这样:

import functools

def decAny(tag):
    def dec(f0):
        @functools.wraps(f0)
        def wrapper(*args, **kwargs):
            return "<%s> %s </%s>" % (tag, f0(*args, **kwargs), tag)
        return wrapper
    return dec

@decAny( 'xxx' )
def test2():
    return 'test1XML'

示例:

>>> print(test2())
<xxx> test1XML </xxx>

请注意,除了解决您遇到的特定问题外,我还通过将*args**kwargs作为包装函数的参数并将它们传递给内部的f0调用,对代码进行了一些改进.装饰.这样一来,您就可以装饰一个可以接受任何数量的位置或命名参数的函数,并且该函数仍然可以正常工作.

Note that in addition to fixing the specific problem you were hitting I also improved your code a bit by adding *args and **kwargs as arguments to the wrapped function and passing them on to the f0 call inside of the decorator. This makes it so you can decorate a function that accepts any number of positional or named arguments and it will still work correctly.

您可以在此处阅读有关functools.wraps()的信息:
http://docs.python.org/2/library/functools.html#functools.wraps

You can read up about functools.wraps() here:
http://docs.python.org/2/library/functools.html#functools.wraps