[英]Can I conditionally change which function I'm calling?
Sorry if this has been asked before, but I couldn't find the words to search that would give me the answer I'm looking for. 对不起,如果以前曾经问过,但是我找不到要搜索的字样,这会给我一些我正在寻找的答案。
I'm writing a script that contains a helper function, which, in turn, can call one of several functions which all take the same parameters. 我正在编写一个包含辅助函数的脚本,该函数反过来可以调用几个函数中的一个函数,这些函数都采用相同的参数。 In this helper function, I end up having strings of this: 在这个辅助函数中,我最终得到了这样的字符串:
if funcName="func1":
func1(p1, p2, p3)
elif funcName="func2":
func2(p1, p2, p3)
elif funcName="func3":
func3(p1, p2, p3)
...
I know that I could use another helper function that would also take the funcName string and distribute it to the appropriate function, but is there a better way to do it? 我知道我可以使用另一个辅助函数,它也可以获取funcName字符串并将其分配给相应的函数,但是有更好的方法吗? What my brain wants to do is this: 我的大脑想要做的是:
funcName(p1, p2, p3)
That way I could call an arbitrary function name if I want to. 这样我可以调用任意函数名称。 Is something like that possible? 有可能吗?
Yes, you can, by using a dict
mapping names to functions: 是的,你可以通过使用dict
映射名称来实现函数:
funcs = dict(
func1=func1,
func2=func2,
func3=func3
)
funcs[funcName](p1, p2, p3)
If you put the functions inside an object like so: 如果将函数放在一个对象中,如下所示:
var funcs =
{
f1: function() {},
f2: function() {},
f3: function() {}
}
You can do funcs['f1']()
for example. 你可以做funcs['f1']()
例如。
You can call them within the locals
or globals
dict: 你可以在locals
或globals
dict中调用它们:
locals()[funcName](p1, p2, p3)
Example: 例:
>>> a = lambda x: x+1
>>> locals()['a'](2)
3
As commented below you may check if they are within expected: 如下所述,您可以检查它们是否符合预期:
if funcName in ["func1", "func2", "func3"]:
locals()[funcName](p1, p2, p3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.