简体   繁体   English

Python中的装饰器

[英]Decorators in Python

Say you have the following code: 假设您有以下代码:

def addTags(functionHere):
    def wrapper():
        return "NumberTag" + functionHere() + "NumberTagOver"
    return wrapper

@addTags
def numbers(firstValue, secondValue):
    return firstValue + secondValue

Then putting numbers(4, 5) into the interpreter spits back a trace saying that wrapper takes no arguments. 然后将数字(4,5)放到解释器中会吐出一条痕迹,说包装器没有参数。 Okay fine, then putting numbers() into the interpreter spits back that numbers wants two arguments! 好的,然后将Numbers()放到解释器中会吐出数字要两个参数! Confused. 困惑。

Your wrapper function replaces the wrapped function, and needs to match the number of arguments it takes. 包装函数将替换包装的函数,并且需要匹配它所接受的参数数量。 Your wrapped function takes two arguments (firstValue, secondValue) , but your wrapper takes none at all. 包装的函数接受两个参数(firstValue, secondValue) ,但是包装器完全不接受。

You could add these two to your decorator wrapper too: 您也可以将这两个添加到装饰包装器中:

def addTags(functionHere):
    def wrapper(firstValue, secondValue):
        return "NumberTag" + functionHere(firstValue, secondValue) + "NumberTagOver"
    return wrapper

but that ties your decorator to that specific function. 但这会将您的装饰器与该特定功能联系在一起。

There is a trick you can use however: 您可以使用以下技巧:

def addTags(functionHere):
    def wrapper(*args):
        return "NumberTag" + functionHere(*args) + "NumberTagOver"
    return wrapper

The *args positional argument acts as a catch-all, all positional arguments to the function are now passed on to the wrapped function. *args位置参数充当一个包罗万象的东西,该函数的所有位置参数现在都传递给包装的函数。

There is an equivalent for keyword arguments too: 关键字参数也有一个等效项:

def addTags(functionHere):
    def wrapper(*args, **kw):
        return "NumberTag" + functionHere(*args, **kw) + "NumberTagOver"
    return wrapper

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM