python - 从字典中调用函数

标签 python arrays function dictionary call

我一直在努力解决这个问题,我找到了一些解决方案,但没有任何乐趣。 基本上我有一本带有按键和相应功能的字典。该词典的目的是链接到特定的支持指南。我接受用户的输入。使用此输入,我搜索字典,如果有按键,则调用该函数。

Python3.6

class Help():
  def load_guide(self):
    while True:

        print("Which Guide would you like to view")

        for manual in Help.manuals:
            print (f"{manual}",end =', ')

        guide_input= input("\n> ")
        if guide_input in Help.manuals:

            Help.manuals.get(guide_input)
            return False 

        else:

            print("Guide not avalible")

  def manual():
      print("Build in progress")
  def introduction():
      print("Build in progress")


  manuals = {
  'Manual' : manual(),
  'Introduction' : introduction()
  }

我尝试了几种变体,但每种变体都会带来不同的问题。

Help.manuals[guide_input] | No action performed 
Help.manuals[str(guide_input)] | Error: TypeError: 'NoneType' object is not callable
Help.manuals[guide_input]() | Error: TypeError: 'NoneType' object is not callable
Help.manuals.get(guide_input) | No action performed

最佳答案

当你像这样初始化你的字典时:

def manual():
    print("Build in progress")

manuals = {'Manual' : manual()}`

manual的返回值函数将存储在字典中,因为您在初始化期间调用了该函数( manuals() 是函数调用)。因为该函数不返回任何内容,所以该值存储在 'Manual' 下的字典中关键是NoneType :

>>> type(manuals['Manual'])
<class 'NoneType'>

因此,您必须更改字典的初始化方式,以便对存储在字典中的函数的引用。您可以通过在字典初始化期间不调用该函数来完成此操作(请注意缺少 () ):

>>> manuals = {'Manual' : manual}
>>> type(manuals['Manual'])
<class 'function'>

那么您所需要的就是使用manuals['Manual']从字典中获取对该函数的引用。 ,并调用该函数 manuals['Manual']() .

>>> manuals['Manual']
<function manual at 0x7fb9f2c25f28>
>>> manuals['Manual']()
Build in progress

关于python - 从字典中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890928/

相关文章:

c++ - 将函数放入头文件的经验法则

ios - 检索/设置数组中 UIView 对象的值

python - PDB - 退出功能

Python unicode 字符串到字符串?

php - 为什么我的 SQL 脚本停止了?

C 获取文件行并将它们放入字符串数组的单独索引中

python - 在 Python 中读取图像文件并计算 Canny 边缘过滤器

python - Pandas 从另一列的字符串切片创建新列

python - 在网址中添加破折号

c++ - 如何在使用for循环和数组时更改为c代码