我正在学习如何使用python的*args*
和{
下面的代码将接受一个控制台输入,然后搜索哪个模块包含该函数放入控制台,然后使用参数执行该函数。在
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个参数?在
如果要将参数传递给函数,则需要在该函数的调用中使用这些参数。
getattr()
不知道要检索的属性,也不接受调用参数。在请执行以下操作:
getattr()
参数只接受对象、要从中检索的属性以及可选的默认值(如果该属性不存在)。在请注意,您也不需要在函数上调用
str()
;您最多可能希望将函数调用的返回值转换为string。在为了回答你所问的问题,getattr只接受两三个参数。传递三个参数并不像你想做的那样:
例如,调用}基本相同。在
getattr(math, "sin")
与写math.sin
是一样的。这将检索math
模块中名为sin
的属性,该属性恰好是一个函数。使用getattr
来做这件事没有什么特别的。如果您编写math.sin(i)
,那么您将从math
模块获取属性sin
,并立即调用它。getattr(math, "sin")(i)
与{由于函数调用就是这样正常工作的,所以您需要以下代码来代替:
^{pr2}$它从模块中获取命令函数,然后正常调用它,就像直接调用模块中的函数一样。但这并不是代码中唯一的错误。接下来,你写下:
这也是错误的。
func
不会被你调用的函数的返回值所替代。如果它是这样工作的,那么在您调用math.sin
之后,就没有人可以再使用math.sin
。存储在变量中的函数与任何其他函数一样,因此您很明显会像任何其他函数一样检索其返回值:除此之外,这段代码似乎还有最后一个错误。
commandList[0:]
什么也不做。你想从第一个元素中分一杯羹。。。。最后一个元素。所有这些只是复制列表。您可能首先想要的是commandList[1:]
,它将获得除命令之外的所有参数。解决这个问题,你会得到:相关问题 更多 >
编程相关推荐