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

2024-10-03 09:09:22 发布

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

我正在学习如何使用python的*args*和{}符号。我尝试使用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))

我尝试使用一个接受参数的命令,比如我做的一个自定义ping命令。但是,我得到了回溯:

^{pr2}$

如何向getattr函数传递多于3个参数?在


Tags: key函数informatforoutput参数value
2条回答

如果要将参数传递给函数,则需要在该函数的调用中使用这些参数。getattr()不知道要检索的属性,也不接受调用参数。在

请执行以下操作:

func = getattr(moduleDict[key], command)
output = func(*args)

getattr()参数只接受对象、要从中检索的属性以及可选的默认值(如果该属性不存在)。在

请注意,您也不需要在函数上调用str();您最多可能希望将函数调用的返回值转换为string。在

为了回答你所问的问题,getattr只接受两三个参数。传递三个参数并不像你想做的那样:

getattr(object, name[, default])

例如,调用getattr(math, "sin")与写math.sin是一样的。这将检索math模块中名为sin的属性,该属性恰好是一个函数。使用getattr来做这件事没有什么特别的。如果您编写math.sin(i),那么您将从math模块获取属性sin,并立即调用它。getattr(math, "sin")(i)与{}基本相同。在

由于函数调用就是这样正常工作的,所以您需要以下代码来代替:

^{pr2}$

它从模块中获取命令函数,然后正常调用它,就像直接调用模块中的函数一样。但这并不是代码中唯一的错误。接下来,你写下:

output = str(func)

这也是错误的。func不会被你调用的函数的返回值所替代。如果它是这样工作的,那么在您调用math.sin之后,就没有人可以再使用math.sin。存储在变量中的函数与任何其他函数一样,因此您很明显会像任何其他函数一样检索其返回值:

func = getattr(moduleDict[key], command)
output = func(*args[1:])

除此之外,这段代码似乎还有最后一个错误。commandList[0:]什么也不做。你想从第一个元素中分一杯羹。。。。最后一个元素。所有这些只是复制列表。您可能首先想要的是commandList[1:],它将获得除命令之外的所有参数。解决这个问题,你会得到:

args = commandList[1:]
func = getattr(moduleDict[key], command)
func(*args)

相关问题 更多 >