Python decorator:TypeError:函数接受1个位置参数,但给出了2个位置参数

2024-04-24 17:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在Python中测试decorators的实用性。当我写以下代码时,有一个错误:

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

我首先将函数log_calls(fn)定义为

^{pr2}$

之后,我使用log_调用将另一个函数修饰为:

@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 given出现。在

我不知道这个装潢工出了什么毛病,怎么修理。在


Tags: or代码lognumberreturnif错误argument
1条回答
网友
1楼 · 发布于 2024-04-24 17:32:20

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

out = fn(args, kwargs)

如果您想应用args元组和kwargs字典作为变量参数,则应重复函数签名语法,因此再次使用*和{}:

^{pr2}$

参见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.

相关问题 更多 >