Python 函数装饰器错误
Python function decorator error
我尝试使用函数装饰器,但在这个例子中它对我不起作用,你能给我解决方案吗?
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
解释器打印错误:"TypeError: decorator() takes 0 positional arguments but 2 were given"
当您使用装饰器时,装饰器中 return 的函数会替换旧函数。也就是说,multiply_by_three
中的decorator
函数替代了add
函数。
这意味着每个函数的签名都应该匹配,包括它们的参数。但是,在您的代码中,add
接受两个参数,而 decorator
接受 none。您还需要让 decorator
接收两个参数。您可以使用 *args
and **kwargs
:
轻松完成此操作
def multiply_by_three(f):
def decorator(*args, **kwargs):
return f(*args, **kwargs) * 3
return decorator
如果您现在装饰您的函数并 运行 它,您可以看到它有效:
@multiply_by_three
def add(a, b):
return a + b
print(add(1,2)) # 9
我尝试使用函数装饰器,但在这个例子中它对我不起作用,你能给我解决方案吗?
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
解释器打印错误:"TypeError: decorator() takes 0 positional arguments but 2 were given"
当您使用装饰器时,装饰器中 return 的函数会替换旧函数。也就是说,multiply_by_three
中的decorator
函数替代了add
函数。
这意味着每个函数的签名都应该匹配,包括它们的参数。但是,在您的代码中,add
接受两个参数,而 decorator
接受 none。您还需要让 decorator
接收两个参数。您可以使用 *args
and **kwargs
:
def multiply_by_three(f):
def decorator(*args, **kwargs):
return f(*args, **kwargs) * 3
return decorator
如果您现在装饰您的函数并 运行 它,您可以看到它有效:
@multiply_by_three
def add(a, b):
return a + b
print(add(1,2)) # 9