Python - 对方法和 while 循环非常困惑

标签 python while-loop

我有这个方法:

def is_active(self):
    if self.is_current_node():
        return True
    cur_children = self.get_children()
    while cur_children is not None:
        for child in cur_children:
            if child.is_current_node():
                return True
            raise Exception(child.display_name)
        cur_children = cur_children.get_children()
    return False

我将这个方法放在一起,并放置了 raise Exception(child.display_name) 来测试并“alert()”我哪个 child 被击中。永远不会引发异常。您可能会认为这是因为该函数在 if child.is_current_node() 部分返回了 True。好吧,如果我用以下内容替换 if 部分:

        for child in cur_children:
            if child.is_current_node():
                raise Exception(child.display_name)

它仍然不会引发异常。但是如果我这样做:

        for child in cur_children:
            raise Exception(child.display_name)

引发异常。我很困惑。我确信这很荒谬,但我才两岁,我还无法用我小小的大脑思考这个问题。

最佳答案

如果列表中的第一个子节点 .is_current_node(),那么您的第一个代码片段中永远不会引发异常。

您拥有的所有证据都支持这样的想法:self.is_current_node() 始终为 true,或者第一个扫描的子节点 .is_current_node()。鉴于第三个代码片段,情况似乎是后者。

编辑:消除误解( child != self ):/

其实我想问一下,这是做什么的?它看起来隐隐约约像递归树遍历,但事实并非如此。 (特别是 cur_children = cur_children.get_children() 行有点奇怪)

关于Python - 对方法和 while 循环非常困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3587345/

相关文章:

python - Linux中的Python和python3有不同的pip吗?

计数器和累加器不工作并导致程序崩溃。我究竟做错了什么?

arrays - 从两个文件中读取变量并以模式输出到第三个文件

c - While 循环在条件出现之前停止

PHP在while循环中添加+1

python - 运行 Luigi 工作流程时没有可视化依赖图

python - 聪明的 any() 之类的函数来检查是否至少有 n 个元素为真?

Python3 中缺少 Python 2's ` exceptions` 模块,它的内容去哪儿了?

python - Python 中的 float ('inf' ) 有什么意义?

c++ - 为什么我的 while 循环永远不会结束,即使生成的整数不符合运行条件