python - 有没有办法在列表或字典中存储函数,以便在调用索引(或键)时触发存储的函数? [英] python - 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?

查看:97
本文介绍了python - 有没有办法在列表或字典中存储函数,以便在调用索引(或键)时触发存储的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我尝试过像 mydict = {'funcList1':[foo(),bar(),goo()],'funcList2':[foo(),goo ),bar()] ,这不起作用。



这种功能有某种结构吗?



我意识到,我可以明显地这样做,就像一堆def语句一样容易:

  def func1():
foo()
bar()
goo()

但是我需要的语句数量变得非常笨重,很难记住。在一个字典中很好地包装它,我可以再次检查钥匙。

解决方案

函数是Python中的第一类对象,因此您可以使用字典进行调度。例如,如果 foo bar 是函数,而 dispatcher 是一个这样的字典。

  dispatcher = {'foo':foo,'bar':bar} 

请注意,值为 foo bar 它们是函数对象,NOT foo() bar()



要调用 foo ,您只需执行 dispatcher ['foo']()



编辑:如果要运行存储在列表中的多个功能,您可以执行此操作。

  dispatcher = {'foobar':[foo,bar],'bazcat':[baz,cat]} 

def fire_all(func_list):func_list中的f

f()

fire_all(dispatcher ['foobar'])
/ pre>

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.

解决方案

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

这篇关于python - 有没有办法在列表或字典中存储函数,以便在调用索引(或键)时触发存储的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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