【问题标题】: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?有没有办法将函数存储在列表或字典中,以便在调用索引(或键)时触发存储的函数?
【发布时间】:2021-04-19 10:29:26
【问题描述】:

例如,我尝试过 mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()] 之类的方法,但不起作用。

是否有某种结构具有这种功能?

我意识到我显然可以用一堆 def 语句轻松地做到这一点:

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

但是我需要的语句数量变得非常笨重且难以记住。将它们很好地包装在字典中会很好,我可以不时检查键。

【问题讨论】:

  • 你在没有意识到的情况下描述了函数式编程:P

标签: python dictionary dispatch


【解决方案1】:

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

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

请注意,这些值是函数对象 foobar,而不是 foo()bar()

要拨打foo,您可以拨打dispatcher['foo']()

编辑:如果你想运行存储在列表中的多个函数,你可以做这样的事情。

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

def fire_all(func_list):
    for f in func_list:
        f()

fire_all(dispatcher['foobar'])

【讨论】:

  • 整洁!我可以在值中存储多个函数吗?那么当我调用键 [foo]() 时,它会运行存储在值中的所有函数?
  • @Zack 在列表中添加了有关多个函数的详细信息
  • 干净整洁,解释清楚
  • 在类的方法中如何工作?所以,如果函数是``` def func1(self) ``` 并且当我们调用它时它必须是self.func1,我们怎么能制作“dispatcher” dict?
  • @PraveenGollakota 有没有办法将函数的参数存储在字典中?我似乎无法弄清楚如何让它发挥作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多