简体   繁体   English

Python函数装饰器错误

[英]Python function decorator error

I tried to use function decorators, but in this example it dooesn't work for me, can you give me the solution ? 我试图使用函数装饰器,但在这个例子中它对我不起作用,你能给我解决方案吗?

def multiply_by_three(f):
    def decorator():
        return f() * 3
return decorator

@multiply_by_three
def add(a, b):  
    return a + b

print(add(1,2)) # returns (1 + 2) * 3 = 9

Interpreter prints error: "TypeError: decorator() takes 0 positional arguments but 2 were given" 解释器打印错误:“TypeError:decorator()需要0个位置参数但是给出了2个”

When you use a decorator, the function you return from the decorator replaces the old function. 当您使用装饰器时,您从装饰器返回的函数将替换旧函数。 In other words, the decorator function in multiply_by_three replaces the add function. 换句话说, multiply_by_threedecorator函数替换了add函数。

This means that each functions signature's should match, including their arguments. 这意味着每个函数签名都应该匹配,包括它们的参数。 However, in your code add takes two arguments while decorator takes none. 但是,在你的代码中, add需要两个参数,而decorator则不需要。 You need to let decorator receive two arguments as well. 你需要让decorator接收两个参数。 You can do this easily by using *args and **kwargs : 您可以使用*args**kwargs轻松完成此操作:

def multiply_by_three(f):
    def decorator(*args, **kwargs):
        return f(*args, **kwargs) * 3
    return decorator

If you now decorate your function and run it, you can see it works: 如果您现在装饰您的功能并运行它,您可以看到它的工作原理:

@multiply_by_three
def add(a, b):  
    return a + b

print(add(1,2)) # 9

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

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