我一直在努力解决这个问题,我找到了一些解决方案,但没有任何乐趣。基本上,我有一本带按键和相应功能的字典。该词典的目的是链接到特定的支持指南。我接受用户的输入。使用此输入,我可以搜索字典,以及是否调用了该函数的键。
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'>
因此,您必须更改字典的初始化方式,以便将对函数的引用存储在dict中。您可以通过在字典初始化期间不调用该函数来完成此操作(请注意缺少的()
):
>>> manuals = {'Manual' : manual}
>>> type(manuals['Manual'])
<class 'function'>
然后,您所需要的是使用manuals['Manual']
从字典中获得对该函数的引用,并调用该函数manuals['Manual']()
。
>>> manuals['Manual']
<function manual at 0x7fb9f2c25f28>
>>> manuals['Manual']()
Build in progress