如何在python的字典中添加函数作为值?
我有另一个.py文件,其中所有函数都是编写的,例如如何在python的字典中添加函数作为值?,python,python-3.x,function,Python,Python 3.x,Function,我有另一个.py文件,其中所有函数都是编写的,例如 def EqualToCheck(value, comparingValue, ExpectedVal:bool): if (value == comparingValue): return ExpectedVal else : return not ExpectedVal def LessThanCheck(value, comparingValue, ExpectedVal:bool):
def EqualToCheck(value, comparingValue, ExpectedVal:bool):
if (value == comparingValue):
return ExpectedVal
else :
return not ExpectedVal
def LessThanCheck(value, comparingValue, ExpectedVal:bool):
if (value < comparingValue):
return ExpectedVal
else :
return not ExpectedVal
我已经导入了py文件,也就是说,我可以访问这些函数,但我需要将这些函数用作字典的值
这样我就可以这样称呼它了
if a == "checkEqual":
callFunc['checkEqual'](5,6,True)
如何操作?在dict定义中使用函数本身,而不调用它们:
callFunc = {
"checkEqual": EqualToCheck,
"lessthanEqual": LessThanCheck,
}
在Python中,函数是一级对象,与任何其他类型的变量位于相同的名称空间中。函数定义创建变量绑定,就像赋值一样。您可以像在任何其他数据类型中一样在表达式中使用这些变量
if a == "checkEqual":
callFunc['checkEqual'](5,6,True)
使用导入语句啊!也许我的问题措辞不对。我已经导入了py文件,也就是说,我可以访问这些函数,但是我需要使用这些函数作为字典的值。那么,到底什么不起作用?假设省略的部分也有效,您的示例不完整,但有效。请再次编辑,希望这有助于
callFunc
字典在定义时调用相等函数,但这可能不是您想要的。
if a == "checkEqual":
callFunc['checkEqual'](5,6,True)