You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python装饰器适配带参数函数报错TypeError,求正确实现方案

问题原因

报错TypeError: mfx.<locals>.mfx() takes 0 positional arguments but 1 was given的核心原因是装饰器的内部包装函数没有定义参数,但被装饰的list_sort函数需要接收一个列表参数。调用list_sort(my_list)时,参数会被传递给装饰器返回的包装函数,但这个函数没有参数定义,因此触发参数不匹配错误。

另外,原list_sort函数还有个隐性错误:参数名是list,但函数内部使用的是my_list,会导致NameError,需要一起修正。

修正方案

1. 修复装饰器,适配带参数的函数

修改装饰器的内部包装函数,使其能接收并传递参数给原函数。使用*args和**kwargs可以让装饰器兼容任意参数的函数,通用性更强:

def mfx(fx):
    def wrapper(*args, **kwargs):
        print("The list has been sorted to:")
        # 将接收的参数传递给原函数
        fx(*args, **kwargs)
    return wrapper

2. 修复排序函数的变量名错误

将函数参数名改为my_list,和内部使用的变量名保持一致;同时建议复制原列表,避免修改外部传入的列表(可选,但更安全):

@mfx
def list_sort(my_list):
    new_list = []
    # 复制原列表,避免修改外部传入的my_list
    temp_list = my_list.copy()
    while temp_list:
        min_val = temp_list[0]
        for x in temp_list:
            if x < min_val:
                min_val = x
        new_list.append(min_val)
        temp_list.remove(min_val)
    print(new_list)

3. 调用方式不变

my_list = [0,10,2,1,8]
list_sort(my_list)
运行结果

执行后会输出:

The list has been sorted to:
[0, 1, 2, 8, 10]

内容的提问来源于stack exchange,提问作者Sukanta Biswas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:13:15