简体   繁体   中英

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. Okay fine, then putting numbers() into the interpreter spits back that numbers wants two arguments! 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.

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.

There is an equivalent for keyword arguments too:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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