TypeError: execute() missing 1 required positional argument: 'args'

TypeError: execute() missing 1 required positional argument: 'args'

如果之前有人问过这个问题,我深表歉意。 我正在尝试创建一个函数,该函数 returns 另一个函数的输出,参数为 func(要执行的函数)和 args(函数的参数)。 烦人的是,我一直收到错误消息。

TypeError: execute() missing 1 required positional argument: 'args'

我不确定问题出在哪里,因为我看不出函数的定义或调用有任何错误。如果有帮助,这里是定义;

def execute(func, args):
 return func(args)

我调用函数的行:

print(function)
print(argument)
execute((function, argument))

完整的输出是:

print
Hello world
Traceback (most recent call last):
  File "C:\Python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "c:\program files (x86)\microsoft visual studio19\community\common7\ide\extensions\microsoft\python\core\debugpy\__main__.py", line 45, in <module>
    cli.main()
  File "c:\program files (x86)\microsoft visual studio19\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 430, in main
    run()
  File "c:\program files (x86)\microsoft visual studio19\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 267, in run_file
    runpy.run_path(options.target, run_name=compat.force_str("__main__"))
  File "C:\Python39\lib\runpy.py", line 268, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Python39\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\willd\source\repos\code executer\code_executer.py", line 52, in <module>
    execute((function, argument))
TypeError: execute() missing 1 required positional argument: 'args'

如果有帮助,我正在使用 Microsoft visual studio 2019 社区。 提前致谢!

您将变量作为元组传递,该元组被计为单个项目。您调用该函数的正确方法是:

execute(function, argument)

你只给 python 一个参数,它是由括号组成的元组。 要正确调用 execute,您需要删除括号,因为 python 将它们解释为一个元组。 元组是不可变的。

execute(function, arguments) 调用使用 2 个参数执行, 相当于execute(func=function, args=arguments)

execute((function, arguments)) 仅使用 1 个参数调用 'execute'。 相当于 execute(func=(function, arguments)) 并且缺少 'arguments'.

建议: 如果你想避免传递参数,请查看 partials。

如果函数有多个位置参数,您应该将代码更改为类似的代码,否则您将 运行 再次遇到同样的问题。:

def execute(function, *args):
    return function(*args)