有没有一种方法可以将函数存储在列表或字典中,以便在调用索引(或键)时会触发存储的函数? [英] Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?
问题描述
例如,我尝试了诸如mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()]
之类的方法,该方法不起作用.
For instance, I've tried things like mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()]
, which doesn't work.
具有某种功能的结构吗?
Is there some kind of structure with this kind of functionality?
我意识到,显然我可以使用一堆def
语句轻松地做到这一点:
I realize that I could obviously do this just as easily with a bunch of def
statements:
def func1():
foo()
bar()
goo()
但是我需要的语句数量变得非常笨拙且难以记住.最好将它们很好地包装在字典中,这样我可以一次又一次地检查它们的键.
But the number of statements I need is getting pretty unwieldy and tough to remember. It would be nice to wrap them nicely in a dictionary that I could examine the keys of now and again.
推荐答案
函数是Python中的第一类对象,因此您可以使用字典进行分派.例如,如果foo
和bar
是函数,而dispatcher
是类似的字典.
Functions are first class objects in Python and so you can dispatch using a dictionary. For example, if foo
and bar
are functions, and dispatcher
is a dictionary like so.
dispatcher = {'foo': foo, 'bar': bar}
请注意,值为函数对象的foo
和bar
,而不是foo()
和bar()
.
Note that the values are foo
and bar
which are the function objects, and NOT foo()
and bar()
.
要呼叫foo
,您只需执行dispatcher['foo']()
如果要运行列表中存储的多个函数,则可以执行以下操作.
If you want to run multiple functions stored in a list, you can possibly do something like this.
dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}
def fire_all(func_list):
for f in func_list:
f()
fire_all(dispatcher['foobar'])
这篇关于有没有一种方法可以将函数存储在列表或字典中,以便在调用索引(或键)时会触发存储的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!