我一直在试图解决这个问题,我找到了一些解决办法,但没有joy。基本上,我有一个带键的字典和一个相应的函数。词典的目的是链接到特定的支持指南。我接受用户的输入。使用此输入,我搜索字典,如果键调用该函数。
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发布于 2019-11-16 13:08:26
当你像这样初始化你的字典:
def manual():
print("Build in progress")
manuals = {'Manual' : manual()}`manual函数的返回值将存储在dict中,因为在初始化期间调用该函数(manuals()是一个函数调用)。因为函数不返回任何内容,所以存储在'Manual'键下的字典中的值是NoneType
>>> type(manuals['Manual'])
<class 'NoneType'>因此,您必须改变字典初始化的方式,以便对dict中存储的函数进行引用。通过在字典初始化期间不调用函数(注意缺少的()),您可以做到这一点:
>>> manuals = {'Manual' : manual}
>>> type(manuals['Manual'])
<class 'function'>然后,您只需使用manuals['Manual']从字典中获得对函数的引用,并调用该函数manuals['Manual']()。
>>> manuals['Manual']
<function manual at 0x7fb9f2c25f28>
>>> manuals['Manual']()
Build in progresshttps://stackoverflow.com/questions/58890928
复制相似问题