You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python递归执行逻辑解析请求:Foo类bar方法输出疑问

Python递归执行逻辑解析

问题背景

编写了如下Python类及执行代码,得到对应输出后,无法理解递归执行过程:当if语句中的第一个bar()调用执行到foo.stop=5后,第二个bar()为何会额外执行4次?

代码实现

Foo类定义

class Foo:
    def __init__(self):
        self.stop = 0

    def bar(self):
        self.stop += 1
        print(self.stop)

        if self.stop < 5:
            print('before first bar')
            self.bar()

            print('before second bar')
            self.bar()

            return None

执行代码

foo = Foo()

foo.bar()

print(f"the value of foo.stop is {foo.stop}")

执行输出

1
before first bar
2
before first bar
3
before first bar
4
before first bar
5
before second bar
6
before second bar
7
before second bar
8
before second bar
9

the value of foo.stop is 9

递归逻辑拆解

递归的核心是调用栈的层级嵌套,每一层bar()调用在执行完第一个递归调用后,才会继续执行第二个递归调用。我们按调用顺序逐层拆解:

  1. 第一层调用(stop=1):
    • stop自增到1,打印1
    • 满足stop<5,打印before first bar,调用bar()进入第二层
  2. 第二层调用(stop=2):
    • stop自增到2,打印2
    • 满足stop<5,打印before first bar,调用bar()进入第三层
  3. 第三层调用(stop=3):
    • stop自增到3,打印3
    • 满足stop<5,打印before first bar,调用bar()进入第四层
  4. 第四层调用(stop=4):
    • stop自增到4,打印4
    • 满足stop<5,打印before first bar,调用bar()进入第五层
  5. 第五层调用(stop=5):
    • stop自增到5,打印5
    • 不满足stop<5,直接退出当前调用,回到第四层
  6. 回到第四层(执行剩余代码):
    • 打印before second bar,调用bar()进入第六层(stop=6,打印6后退出),第四层执行完毕回到第三层
  7. 回到第三层(执行剩余代码):
    • 打印before second bar,调用bar()进入第七层(stop=7,打印7后退出),第三层执行完毕回到第二层
  8. 回到第二层(执行剩余代码):
    • 打印before second bar,调用bar()进入第八层(stop=8,打印8后退出),第二层执行完毕回到第一层
  9. 回到第一层(执行剩余代码):
    • 打印before second bar,调用bar()进入第九层(stop=9,打印9后退出),第一层执行完毕退出

简单来说,当递归走到stop=5触底后,会沿着之前的调用栈从最内层向外层依次返回,每返回一层就会执行该层第一个递归调用后的代码——也就是打印before second bar并调用一次bar()。这样的返回层级一共有4层(第四、第三、第二、第一层),所以会额外执行4次bar(),对应stop从6增加到9。

内容的提问来源于stack exchange,提问作者alpastor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:46:07