[英]Store functions in list and call them later
I want to store functions in a list and then later in a program call those functions from that list. 我想将函数存储在列表中,然后在程序中调用该列表中的那些函数。
This works for me, however, I don't know if it is correct : 这对我有用,但是,我不知道它是否正确:
#example functions, my functions would actually get user input etc.
def func1():
return 2
def func2():
return 3
options = [ func1, func2 ]
#call functions
options[0]()
Is this the proper way to store functions in a list and call it ? 这是将函数存储在列表中并调用它的正确方法吗? Or is there a different, better way to do this?
或者有更好的方法来做到这一点吗?
Yes, you can do it. 是的,你可以做到。 If you want to call all functions in the list with a "one liner" you can do the following:
如果要使用“单行”调用列表中的所有功能,可以执行以下操作:
results = [f() for f in options]
Yes, this is correct, though if your functions are really one-liner in nature, I would suggest you also have a look at lambdas
, so that your entire code can be reduced to: 是的,这是正确的,但如果你的功能本质上是单行的,我建议你也看看
lambdas
,这样你的整个代码就可以简化为:
options = [lambda: 3, lambda: 2]
As already pointed out in comments, you will Of course need to remember the order of the functions in the list. 正如评论中已经指出的那样,您当然需要记住列表中函数的顺序。
I like to do things like 我喜欢做类似的事情
class Commander:
def CommandERROR(*args,**kwargs):
print "Invalid command"
def CommandFunc1(*args,**kwargs):
print "Do Command 1"
def CommandFunc2(*args,**kwargs):
print "Do Command 2"
def CallCommand(command,*args,**kwargs):
self.__dict__.get("Command"+command,self.CommandError)(*args,**kwargs)
cmd = Commander()
cmd.CallCommand("Func1","arg1",something=5)
cmd.CallCommand("Func2","arg2",something=12)
cmd.CallCommand("Nothing","arg1",something=5)
as pointed out in the comments you can also put this in its own file to create the namespace and ommit the class ... although if you need to affect state then maybe a class is a better option ... you could also use a simple dict 正如在评论中指出的那样,你也可以将它放在自己的文件中来创建命名空间并省略该类...虽然如果你需要影响状态那么也许一个类是一个更好的选择...你也可以使用一个简单的字典
Not sure how others do it, but I do it the same way. 不确定别人怎么做,但我也是这样做的。 It's perfect for my basic codes, hence I believe they can be used elsewhere too.
它非常适合我的基本代码,因此我相信它们也可以在其他地方使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.