首页 > 解决方案 > Python 在组合两个静态方法时给出不同的结果

问题描述

我通过将静态方法node_provides_f_through_p_branchdeps_search_step(左)组合成一个更简单deps_search_step的(右)来简化代码。

注意左边第829行返回了一个类型为的节点,PlanOperator相当于使用了if isinstance(reuslt, PlanOperator)--if,下面注释的A和B应该没问题。

然而,我得到不同的结果。尽管我没有全局变量,也没有类变量,但有些东西使代码表现得很奇怪:

在此处输入图像描述

这怎么可能?

这些变量都不是全局变量或任何相关变量。

这是左边的代码:

class PlanExpressionsGraph:
    @staticmethod
    def deps_search_step(G, n, f) -> ResultsPromises:
        """
        Single search step. Returns both the found hits for any of the parent nodes, or continuations
        in case that parent branch still retrieved no result.
        """
        node_deps, continuations = [], []
        for p in G.predecessors(n):
            result = PlanExpressionsGraph.node_provides_f_through_p_branch(G, n, p, f)
            if isinstance(result, PlanOperator):  # if A
                node_deps.append(result)
            else:                                 # else (B)
                continuations.append(result)
        return node_deps, continuations

    @staticmethod
    def node_provides_f_through_p_branch(G, n, p, f):
        f_prime = n.translate_deps_ids(G, p, [f])[0]
        if f_prime in p.get_provided_deps_ids():  # will enter `if A`
            return p  # type = PlanOperator
        else:  
            # will go to (B)
            return lambda: PlanExpressionsGraph.deps_search_step(G, p, f_prime)

这是右边的代码:

class PlanExpressionsGraph:
    @staticmethod
    def deps_search_step(G, n, f) -> ResultsPromises:
        """
        Single search step. Returns both the found hits for any of the parent nodes, or continuations
        in case that parent branch still retrieved no result.
        """
        node_deps, continuations = [], []
        for p in G.predecessors(n):
            f_prime = n.translate_deps_ids(G, p, [f])[0]
            if f_prime in p.get_provided_deps_ids():  # if A
                node_deps.append(p)
            else:                                     # else (B)
                continuations.append(lambda: PlanExpressionsGraph.deps_search_step(G, p, f_prime))
        return node_deps, continuations

注意:我不能共享输入数据或代码库的其余部分,因为它很敏感。

顺便说一句,正确的结果是左边的代码。

谢谢你。

标签: pythonpython-3.x

解决方案


很难确定,因为我无法运行代码来重现您所看到的行为,但我预计不同之处在于,在您修改后的代码中,lambda 使用的一些变量在循环内发生了变化,所以如果稍后执行,lambda 总是会获取循环的最后一个值。在您的第一个示例中,这些值绑定在node_provides_f_through_p_branch.

您应该能够使用如下表达式绑定 lambda 中的值:

lambda G=G, p=p, f_prime=f_prime: PlanExpressionsGraph.deps_search_step(G, p, f_prime)


推荐阅读