如何在不编写多个if语句的情况下调用特定方法?

时间:2019-10-10 17:45:39

标签: python-3.x class dictionary

我想从Function App中的Azure函数调用一系列方法-获取,更新,重建和追加。尽管很容易为此创建四个if语句,但这似乎是一种微不足道的方法。我认为可以使用dict[keyword]:function()类型的操作来解析所需的功能,然后通过查找与该功能相对应的键来调用它,而不是使用一系列的if语句:

# hashable dict of keywords and functions
    etl_func_dict=dict()
    etl_func_dict["Update"]=UpdateFunc()
    etl_func_dict["Append"]=AppendFunc()
    etl_func_dict["Rebuild"]=RebuildFunc()


    etl_func_dict[name]

其中name是沿着查询字符串传递的参数。 当我构建此字典时,输出是预期的,但是检查日志显示在构建字典时也执行了这些功能:

Executing 'Functions.recreate-etl-dict' (Reason='This function was programmatically called via the host APIs.', Id=681bf979-464a-4f33-9fd8-bcbc2b30232d)
[10/10/2019 4:58:10 PM]  INFO: Received FunctionInvocationRequest, request ID: c529a334-197e-44f2-a3a1-6dc7a9c875e0, function ID: c4bf936a-c34a-4f97-b353-f86cd66ff230, invocation ID: 681bf979-464a-4f33-9fd8-bcbc2b30232d
[10/10/2019 4:58:10 PM]  INFO: Successfully processed FunctionInvocationRequest, request ID: c529a334-197e-44f2-a3a1-6dc7a9c875e0, function ID: c4bf936a-c34a-4f97-b353-f86cd66ff230, invocation ID: 681bf979-464a-4f33-9fd8-bcbc2b30232d
[10/10/2019 4:58:10 PM] UpdateFunc Running...
[10/10/2019 4:58:10 PM] AppendFunc Running...
[10/10/2019 4:58:10 PM] RebuildFunc Running...

浏览其他模块的一些文档(例如requests)使我相信,我在这里需要两个类-一个类存储要创建的方法,另一个类创建该模块的实例。基于传递的输入的头等舱。但是,作为Python的新手,我不确定如何实现此目标,甚至不确定这是否是实现此目标的正确方法。

def main(req: func.HttpRequest) -> func.HttpResponse:
    def UpdateFunc(self):
        logging.info("UpdateFunc Running...")
        stringy="Update"
        return stringy
    def AppendFunc(self):
        logging.info("AppendFunc Running...")
        stringy="Append"
        return stringy
    def RecreateFunc(self):
        logging.info("RecreateFunc Running...")
        stringy="Recreate"
        return stringy
    # hashable dict of keywords and functions
    etl_func_dict=dict()
    etl_func_dict["Update"]=UpdateFunc()
    etl_func_dict["Append"]=AppendFunc()
    etl_func_dict["Recreate"]=RecreateFunc()

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    try:
        s = etl_func_dict[name]
        return func.HttpResponse(s,
                                 status_code=200)
    except:
        if not name:
            return func.HttpResponse(
                 "Please pass a name on the query string or in the request body",
                 status_code=400
            )
        else:
            return func.HttpResponse("Name did not match a valid key. Expected values are: {}".format(list(etl_func_dict.keys())))

    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body.",
             status_code=400
        )

如果在不运行函数的情况下初始化了字典,则不需要询问任何问题。有了函数字典,我得到了预期的输出,它在创建字典时也运行了所有函数,我不知道如何避免这种情况。

1 个答案:

答案 0 :(得分:2)

您快到了……如果您不希望在将函数加载到dict时实际调用这些函数,则不要。

etl_func_dict["Update"] = UpdateFunc
etl_func_dict["Append"] = AppendFunc
etl_func_dict["Recreate"] = RecreateFunc

离开括号将存储对函数的引用,而无需实际调用它们。只要确定要调用该函数即可。例如:

s = etl_func_dict[name]()