简体   繁体   English

递归在 python(递归的源代码)内部如何工作?

[英]How does recursion work internally in python (source code of recursion)?

I would like to understand the internal work of recursion.我想了解递归的内部工作。 Can I write my own recursion for python?我可以为 python 编写自己的递归吗?

For example, now we have following function:例如,现在我们有以下 function:

def fact(n):
    return n*fact(n)

How can I change the return command and change the functionality of it, like the following:如何更改返回命令并更改其功能,如下所示:

def fact(n):
    my_return  n*fact(n)

In this case, I want to change the internal work of return and use my_returne, and also with this, I want to control stack differently.在这种情况下,我想改变 return 的内部工作并使用 my_returne,同时我想以不同的方式控制堆栈。

If you want to understand the guts of how Python works, I highly recommend reading the documentation for the built-in modules under the "Language Services" heading, particularly the ast and dis modules.如果您想深入了解 Python 的工作原理,我强烈建议您阅读“语言服务”标题下的内置模块文档,尤其是astdis模块。 Python exposes, as importable and Python-runnable modules, all of its parsing capabilities. Python 将其所有解析功能公开为可导入和 Python 可运行的模块。 You can see, use, and tinker with its parsing of code, how it generates bytecode, and its core execution.您可以查看、使用和修改它的代码解析、它如何生成字节码以及它的核心执行。

I'm not sure if this really helps, but RETURN_VALUE is its own opcode in Python's bytecode, so aside from creating your own bytecode manually or screwing with the parser results, there's probably no other way to get the return keyword's behavior.我不确定这是否真的有帮助,但RETURN_VALUE是 Python 字节码中它自己的操作码,所以除了手动创建自己的字节码或搞砸解析器结果之外,可能没有其他方法可以获取return关键字的行为。 The actual implementation of how that behaves is going to be implementation-dependent (CPython might do it differently from Pypy, for example), so you'd need to be more specific in your question, or just dig into their source code for that opcode.其行为方式的实际实现将取决于实现(例如,CPython 的执行方式可能与 Pypy 不同),因此您需要在您的问题中更加具体,或者只是深入研究该操作码的源代码.

That said, there's nothing stopping you from creating your own stack as a list and pushing/popping stack frames to/from it yourself, besides the sheer insanity of the act.也就是说,没有什么能阻止您将自己的堆栈创建为列表并自己向/从它推送/弹出堆栈帧,除了行为的纯粹精神错乱。 Eg,例如,

stack = []

def my_pseudo_func():
    global stack
    args, kwargs = stack[-1]
    x, = args
    # do some stuff
    my_return_result = x + 5
    ###
    stack.pop()
    stack.append(my_return_result)

stack.append(((3,), {}))
my_pseudo_func()
result = stack.pop()
assert result == 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM