python - Python 在组合两个静态方法时给出不同的结果
问题描述
我通过将静态方法node_provides_f_through_p_branch
与deps_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
注意:我不能共享输入数据或代码库的其余部分,因为它很敏感。
顺便说一句,正确的结果是左边的代码。
谢谢你。
解决方案
很难确定,因为我无法运行代码来重现您所看到的行为,但我预计不同之处在于,在您修改后的代码中,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)
推荐阅读
- python - Numpy中第二维的点积?
- python - hvplot.box 中的不同颜色
- reactjs - 我想在单击提交按钮一次并删除以前的映射项后控制台记录值,但它不起作用
- c# - 是否可以阻止我的 log4net 控制台日志出现在 nunit 控制台运行程序测试输出中
- css - 我怎样才能给这个blob svg一个滚动变形效果?
- php - eval() 和 file_get_contents() .. 不同的结果
- javascript - ng-Include 在 ng-include 中,都绑定到不同的控制器
- javascript - 通过 JavaScript 控制单个元素的多个关键帧动画
- javascript - Svelte 派生存储和数组排序
- c# - 基于 Wix 安装程序的 TopShelf Windows 服务无法启动