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?

◇◆丶佛笑我妖孽 提交于 2019-11-26 05:55:45

问题


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?

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.


回答1:


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}

Note that the values are foo and bar which are the function objects, and NOT foo() and bar().

To call foo, you can just do dispatcher['foo']()

EDIT: 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'])


来源:https://stackoverflow.com/questions/9205081/is-there-a-way-to-store-a-function-in-a-list-or-dictionary-so-that-when-the-inde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!