如何将超过 3 个参数传递给 getattr?

Dor*_*ore 1 python traceback

我正在学习如何使用 python*args***kwargs符号。我正在尝试使用 getattr 将可变数量的参数传递给另一个文件中的函数。

以下代码将接受控制台输入,然后搜索包含放入控制台的函数的模块,然后使用参数执行该函数。

while True:
    print(">>>", end = " ")
    consoleInput = str(input())
    logging.info('Console input: {}'.format(consoleInput))
    commandList = consoleInput.split()
    command = commandList[0]
    print(commandList) # Debug print
    """Searches for command in imported modules, using the moduleDict dictionary,
    and the moduleCommands dictionary."""
    for key, value in moduleCommands.items():
        print(key, value)
        for commands in value:
            print(commands, value)
            if command == commands:
                args = commandList[0:]
                print(args) # Debug print
                print(getattr(moduleDict[key], command))
                func = getattr(moduleDict[key], command, *args)
                func()
                output = str(func)
    else:
        print("Command {} not found!".format(command))
        output = ("Command {} not found!".format(command))
    logging.info('Console output: {}'.format(output))
Run Code Online (Sandbox Code Playgroud)

我尝试使用带参数的命令,例如我制作的自定义 ping 命令。但是,我得到了这个回溯:

Traceback (most recent call last):
  File "/home/dorian/Desktop/DEBPSH/DEBPSH.py", line 56, in <module>
    func = getattr(moduleDict[key], command, *args)
TypeError: getattr expected at most 3 arguments, got 4
Run Code Online (Sandbox Code Playgroud)

如何向getattr函数传递 3 个以上的参数?

Mar*_*ers 5

如果要将参数传递给函数,则需要在调用该函数时使用这些参数getattr()对您正在检索的属性一无所知,并且不接受调用参数。

改为这样做:

func = getattr(moduleDict[key], command)
output = func(*args)
Run Code Online (Sandbox Code Playgroud)

getattr()参数仅采用对象、要从中检索的属性以及一个可选的默认值(如果该属性不存在)。

请注意,您也不需要调用str()该函数;充其量您可能希望将函数调用的返回值转换为字符串。