从字典中调用函数
Call function from within dictionary
我一直在努力解决这个问题,我找到了一些解决方案,但没有任何乐趣。
基本上我有一本带键和相应功能的字典。字典的目的是 link 到特定的支持指南。我接受用户的输入。使用此输入,我搜索字典,如果是键,则调用该函数。
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
函数的 return 值将存储在字典中,因为您在初始化期间调用了该函数(manuals()
是函数调用)。因为该函数没有 return 任何东西,所以 '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
我一直在努力解决这个问题,我找到了一些解决方案,但没有任何乐趣。 基本上我有一本带键和相应功能的字典。字典的目的是 link 到特定的支持指南。我接受用户的输入。使用此输入,我搜索字典,如果是键,则调用该函数。
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
函数的 return 值将存储在字典中,因为您在初始化期间调用了该函数(manuals()
是函数调用)。因为该函数没有 return 任何东西,所以 '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