将函数存储在列表中,以后再调用 [英] Store functions in list and call them later

查看:56
本文介绍了将函数存储在列表中,以后再调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将函数存储在列表中,然后在程序中从该列表中调用这些函数.

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, 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:

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.

这篇关于将函数存储在列表中,以后再调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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