如果一个函数直接或者间接调用了自己,那么就形成了递归(recursion),比如斐波那契数列的一个实现
def fib(n): if n <= 2: return 1 else: return fib(n - 1) + fib(n - 2)
递归一定要有结束条件,否则就形成了死循环, 比如下面的例子:
def a(): b() def b(): a() if __name__ == '__main__': a()
很快 就会抛出一个异常:
RuntimeError: maximum recursion depth exceeded
会什么报这个异常,很简单,我们都知道子程序调用(call)需要压栈出栈,如果无限递归调用,那么就一直压栈,没有出栈,内存消耗也越来愈多。python比较高级,直接抛出这个异常,结束程序运行。
前面的文章提到协程(coroutine)这个概念,不管是generator还是greenlet,语法看起来都很像函数调用,但事实上并不是,协程只是在切换的时候把当前调用栈中的信息存储了起来:
“all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator’s method