如何在python的字典中添加函数作为值?
我有另一个.py文件,所有的函数都写在这个文件中。
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文件调用这些函数,如果我的数据有一个特定的字符串,我想在那里调用这些函数。
使用dict定义中的函数本身,而不调用它们:
callFunc = {
"checkEqual" : EqualToCheck,
"lessthanEqual" : LessThanCheck,
}
在Python中,函数是first-class对象,它们与任何其他类型的变量位于相同的命名空间中。函数定义像赋值一样创建变量绑定。您可以像任何其他数据类型一样在表达式中使用这些变量。
if a == "checkEqual":
callFunc['checkEqual'](5,6,True)