【问题标题】:Is there a way to have functions as values of a dictionary?有没有办法将函数作为字典的值?
【发布时间】:2020-07-12 11:24:21
【问题描述】:

我必须通过从用户那里获取关于要以字符串形式执行的操作的输入来执行多项操作。所以我正在考虑使用一个字典,其中函数名是键,值是函数本身。我还想将参数传递给函数。有没有办法做到这一点? 这就是我想做的:

a = [] # an empty list
inp = input() # which function to apply?
arg = int(input()) # the argument corresponding to the function.

# a dictionary mapping all the functions to the names
func_dict = {"append":a.append(), "pop":a.pop(), "extend": a.extend()} 

我知道这行不通,我也想给出用户输入的参数。有没有办法做到这一点?

谢谢。

【问题讨论】:

  • 你不能用switch case来做这个吗??
  • 我不认为 python 有一个 switch case,我从来没有见过有人使用它,也没有找到任何关于我害怕的文档。
  • 不知道!我想知道他们为什么省略它!

标签: python python-3.x list function dictionary


【解决方案1】:

只需从函数中删除()

a = [] # an empty list
inp = input() # which function to apply?
arg = int(input()) # the argument corresponding to the function.

# a dictionary mapping all the functions to the names
func_dict = {"append":a.append, "pop":a.pop, "extend": a.extend} 

这样您将获得函数的引用而不是其结果。

编辑:然后调用函数,使用func_dict['append'](arg)。请注意,如果您的函数具有不同数量的参数,则此解决方案可能会失败,因此您可能需要在调用函数之前进行检查。

【讨论】:

  • 非常感谢朋友的回答。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
相关资源
最近更新 更多