Warm tip: This article is reproduced from serverfault.com, please click

其他-如何在Python的字典中添加功能作为值?

(其他 - How to add function as Value in dictionary in python?)

发布于 2020-11-28 04:49:53

我还有另一个.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文件中调用这些函数,如果我的数据具有特定的字符串,我想在这些文件中调用这些函数。例如

callFunc = {
 "checkEqual" : EqualToCheck(value, comparingValue, ExpectedVal),
 "lessthanEqual" : LessThanCheck(value, comparingValue, ExpectedVal)
}

我已经导入了py文件,即可以访问这些功能,但是我需要将这些功能用作字典的值。

这样我就可以这样称呼它

if a == "checkEqual":
   callFunc['checkEqual'](5,6,True)

我该怎么做?

Questioner
krishna lodha
Viewed
11
gilch 2020-11-29 02:48:30

在dict定义中使用函数本身,而无需调用它们:

callFunc = {
 "checkEqual": EqualToCheck,
 "lessthanEqual": LessThanCheck,
}

在Python中,函数是一类对象,它们与任何其他类型的变量都位于相同的名称空间中。函数定义会像赋值一样创建变量绑定。你可以像其他任何数据类型一样在表达式中使用这些变量。

if a == "checkEqual":
   callFunc['checkEqual'](5,6,True)