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