【问题标题】:How to call specific method without writing several if statements?如何在不编写多个 if 语句的情况下调用特定方法?
【发布时间】:2019-10-10 17:45:39
【问题描述】:

我想从函数应用程序中的 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
        )

如果字典在没有运行函数的情况下进行了初始化,那么就不需要提出问题。使用函数字典,我得到了预期的输出,它只是在创建字典时运行所有函数,我不知道如何避免这种情况。

【问题讨论】:

    标签: python-3.x class dictionary


    【解决方案1】:

    你快到了...如果你不想在将函数加载到字典时实际调用它们,那就不要。

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

    省略括号会存储对函数的引用,而无需实际调用它们。只要确保在需要时调用该函数。例如:

    s = etl_func_dict[name]()
    

    【讨论】:

    • 还有@HelpfulHound,知道这种技术适用于任何lambda 或内置函数。
    • 我知道这将是这样简单的事情。谢谢!标记为答案。
    猜你喜欢
    • 2019-03-06
    • 1970-01-01
    • 2021-09-29
    • 2019-08-11
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    相关资源
    最近更新 更多