如何将函数调用添加到列表? [英] How to add a function call to a list?

查看:124
本文介绍了如何将函数调用添加到列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用以下函数的Python代码:

  def func1(arguments a,b,c):$ 
$ b def func2(参数d,e,f):

def func3(参数g,h,i):
pre>

以上每个函数都会在产品上配置CLI命令。



此外,对于上述每个函数,都有删除CLI命令的de-init函数。

  def de_init_func1(参数x,y,z):

def de_init_func2(参数l,m,n):

def de_init_func3(arguments q,r,s):

假设我有一个脚本可以配置很多CLI命令使用函数func1,func2和func3,并且在脚本完成之前,脚本应该删除它配置的所有CLI命令。

为了实现这种情况,每次调用func1 / 2/3时,都需要将等效的de_init_func CALL添加到列表中,因此在脚本结尾处,我可以迭代这个列表,并逐个调用de-init方法。



如何在列表中添加func1(arguments)调用到列表中,而不需要调用它。



如果我只是将func1(arguments)调用添加为字符串func1(arguments),那么一旦我迭代列表,我就无法调用函数调用,因为解释器会将列表项作为字符串引用而不是函数调用...

级别,你可以简单地使用元组来引用函数调用。例如,调用 func1(a,b,c)将被元组(func1,a,b,c) code>。然后你可以安全地把这些元组放在一个列表中。

稍后执行这个元组表示的函数(比如 t

  t [0](* t [1:])

即:用t中的参数调用t [0]中的函数。


I have a Python code that uses the following functions:

def func1(arguments a, b, c):

def func2(arguments d, e, f):

def func3(arguments g, h, i):

Each of the above functions configures a CLI command on a product.

In addition, for each of the above functions, there is the de-init function which deletes the CLI command.

def de_init_func1(arguments x, y, z):

def de_init_func2(arguments l, m, n):

def de_init_func3(arguments q, r, s):

Suppose I have a script which configures lots of CLI commands using the functions func1, func2 and func3, and before the script completes, the script should remove all the CLI commands that it configured.

For this to happen, each time func1/2/3 is invoked, I need to add the equivalent de_init_func CALL to a list, so by the end of the script, I can iterate this list, and invoke the de-init methods one by one.

How can I add a "func1(arguments) call" to a list without invoking it while adding it to the list.

If I will just add the func1(arguments) call as a string "func1(arguments)", once I will iterate the list, I won`t be able to invoke the function calls because interpreter will refer to the list items as strings and not as function calls...

解决方案

At the simplest level, you can simply use tuples for referencing function calls. For example, a call to func1(a, b, c) would be referenced by the tuple (func1, a, b, c). You can then safely put those tuples in a list.

To execute later the function represented by such a tuple (say t), simply use :

t[0](*t[1:])

That is : call the function in t[0] with the arguments in the remaining of typle.

这篇关于如何将函数调用添加到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆