这是我的代码:
def funcWithParam(param):
print "Your parameter is: " + param
def justFunction():
print "No parameters"
def wrong():
print "wrong choice"
userInput = raw_input("type 'params' for parameters. type 'no' for no parameters: ")
if userInput == "params":
myparam = "type your parameter: "
else:
myparam = ""
dic = {
"params": (funcWithParam(myparam)),
"no": justFunction,
}
dic.get(userInput,wrong)()
我知道代码是错误的,每次运行它时,“params”键都会与“userInput”字符串一起执行。如果参数检查为 True
并且我添加第二个参数,则程序失败并显示:
'NoneType' object is not callable.
我想知道使用字典调用带有参数的函数的正确语法/方法是什么。
最佳答案
那是因为你构建的字典如下:
dic = {
"params": (funcWithParam(myparam)), #here you already call the function
"no": justFunction, #this is a real function
}
这意味着字典不包含“params”
的函数,但包含该函数的结果。如果您稍后从字典中获取 "params"
,它将返回 None
(因为 funcWithParam
返回 None
),然后您尝试调用不受支持的 None
(如 None()
)。
您可以简单地将字典转换为惰性字典:
dic = {
"params": (lambda : funcWithParam(myparam)),
"no": justFunction,
}
或者更优雅:
dic = {
"params": (lambda x=myparam : funcWithParam(x)),
"no": justFunction,
}
lambda : funcWithParam(myparam)
生成一个不带参数的匿名函数,该函数将使用 myparam
调用 funcWithParam
。
关于python - 使用字典调用带有参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41738762/