sie*_*500 3 python decorator python-3.x python-decorators
我试图使用函数装饰器,但在这个例子中它对我不起作用,你能给我解决方案吗?
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
Run Code Online (Sandbox Code Playgroud)
解释器打印错误:"TypeError:decorator()需要0个位置参数但是给出了2个"
当您使用装饰器时,您从装饰器返回的函数将替换旧函数.换句话说,该decorator功能multiply_by_three取代了该add功能.
这意味着每个函数签名都应该匹配,包括它们的参数.但是,在您的代码中add需要两个参数,而不decorator需要.您还需要decorator接收两个参数.您可以使用*args和**kwargs轻松完成此操作:
def multiply_by_three(f):
def decorator(*args, **kwargs):
return f(*args, **kwargs) * 3
return decorator
Run Code Online (Sandbox Code Playgroud)
如果您现在装饰您的功能并运行它,您可以看到它的工作原理:
@multiply_by_three
def add(a, b):
return a + b
print(add(1,2)) # 9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |