我一直在尝试在字典中存储并调用字符串和/或函数
def mainfunction():
dict = {
'x' : secondfunc,
'y' : 'hello world'
}
while True :
inpt = input('@')
dict[inpt]()
def secondfunc():
print('hi world')
mainfunction()
仅当我输入键“x”时,此操作才有效。 如果我尝试输入键“y”,我会得到这个错误
TypeError: 'str' object is not callable
另外,这个方法的问题是它不能给出默认答案
def mainfunction():
dict = {
'x' : secondfunc,
'y' : 'hello world'
}
while True:
inpt = input('@')
z = dict.get(inpt, 'Default text')
print(z)
def secondfunc():
print('hi world')
mainfunction()
此方法适用于键“y”,但对于键“x”,它会打印出以下内容:
<function secondfunc at 0x7ab4496dc0>
我试图使它,无论我输入哪个值,它将打印一个默认值,打印一个字符串,或执行一个函数。所有这些都取决于按键输入
我找到的唯一解决方案是使用if
语句
def mainfunction():
dict = {
'x' : secondfunc,
}
dict2 = {
'y' : 'hello world'
}
while True:
inpt = input('@')
z = dict2.get(inpt, 'Default text')
if inpt == 'x':
dict[inpt]()
else:
print(z)
def secondfunc():
print('hi world')
mainfunction()
这个解决方案需要的代码比我希望的要多,而且它还需要特定于给定字典的if
语句,这需要更多的时间。
难道没有更好的办法吗
您可以使用
callable()
内置函数测试给定对象是否可调用您可以使用
callable()
函数来测试字典值是否为函数。如果是,则调用它,否则只需打印值本身您需要在字典中存储一个返回字符串的函数,而不是字符串本身
最简单的是,可以使用
lambda
语法作为匿名函数执行此操作:(将此字典命名为
dict
是一种不好的做法,因为它隐藏了内置的dict
,因此我将在这里使用更好的名称。)当然,
secondfunc
不应该打印字符串,但是也应该返回字符串,因为打印已经是mainfunc
的工作了(另请参见:Difference between returns and printing in python?):现在
print(answers['x']())
和print(answers['y']())
正在平等地工作要使用dictionary
.get()
方法创建默认答案,它还需要是一个返回字符串的函数:相关问题 更多 >
编程相关推荐