gpt4 book ai didi

Python装饰器: TypeError: function takes 1 positional argument but 2 were given

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:14 25 4
gpt4 key购买 nike

我正在尝试测试 Python 中装饰器的实用性。当我编写以下代码时,出现错误:

TypeError: fizz_buzz_or_number() takes 1 positional argument but 2 were given

我首先定义一个函数log_calls(fn)

def log_calls(fn):
''' Wraps fn in a function named "inner" that writes
the arguments and return value to logfile.log '''
def inner(*args, **kwargs):
# Call the function with the received arguments and
# keyword arguments, storing the return value
out = fn(args, kwargs)

# Write a line with the function name, its
# arguments, and its return value to the log file
with open('logfile.log', 'a') as logfile:
logfile.write(
'%s called with args %s and kwargs %s, returning %s\n' %
(fn.__name__, args, kwargs, out))

# Return the return value
return out
return inner

之后,我使用 log_calls 将另一个函数装饰为:

@log_calls
def fizz_buzz_or_number(i):
''' Return "fizz" if i is divisible by 3, "buzz" if by
5, and "fizzbuzz" if both; otherwise, return i. '''
if i % 15 == 0:
return 'fizzbuzz'
elif i % 3 == 0:
return 'fizz'
elif i % 5 == 0:
return 'buzz'
else:
return i

当我运行以下代码时

for i in range(1, 31):
print(fizz_buzz_or_number(i))

出现错误 TypeError: fizz_buzz_or_number() Takes 1 Positional argument but 2 were Gived

我不知道这个装饰器有什么问题,以及如何解决这个问题。

最佳答案

您将在此处向您的修饰函数传递 2 个参数:

out = fn(args, kwargs)

如果您想申请args元组和 kwargs字典作为变量参数,回显函数签名语法,因此使用 ***再次:

out = fn(*args, **kwargs)

请参阅Call expressions reference documentation :

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from these iterables are treated as if they were additional positional arguments.

[...]

If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments.

关于Python装饰器: TypeError: function takes 1 positional argument but 2 were given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42573566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com