Skip to main content
 首页 » 编程设计

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

2025年05月04日18落叶无声

我正在学习如何使用 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)) 

我尝试使用带参数的命令,例如我制作的自定义 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 

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

请您参考如下方法:

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

改为这样做:

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

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

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