引用或复制python递归变量? [英] python recursive variables referenced or copied?

查看:42
本文介绍了引用或复制python递归变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下递归函数,但我无法弄清楚 python 如何处理递归函数中的变量.它会为每次递归创建一个 addresses 变量的副本,还是会覆盖该变量并造成可怕的混乱?

I have the following recursive function, and I'm having trouble figuring out how python handles variables in recursive functions. Will it create a copy of the addresses variable for every recursion, or will it overwrite the variable and create a horrible mess?

def get_matches():
    addresses = get_addresses()

    #do stuff

    for addr in addresses:
        #do stuff
        if some_condition:
            get_matches()
        else:
            return

推荐答案

您正在寻找的下划线概念称为框架.

The underlining concept your looking for is called a frame.

Python 解释器的内部是一个堆栈,通常称为调用堆栈.每次 Python 在执行过程中遇到函数调用时,都会创建一个新的框架对象并将其压入堆栈.框架代表函数调用.每个都有自己的作用域,以及传递给函数的任何参数的当前值.

Inside of the Python interpreter is a stack commonly referred to as the call stack. Each time Python encounters a function call during execution, a new frame object is created and pushed on the stack. The frame represents the function call. Each one has it's own scope, and the current value of any arguments passed into the function.

这意味着即使对于函数的每次递归调用,也会为该特定函数调用创建一个新框架并将其压入堆栈.正如我上面已经说过的,每个框架都有自己的范围.因此,每个帧的范围都定义了一个 address 变量,与其他变量分开.

This means that even for each recursive call of a function, a new frame is created for that specific function call and pushed on the stack. As I already said above, each frame has it's own scope. So each frames' scope has an address variable defined in it, separate from any other.

但是请注意,框架对象本身并不存储变量的.您会看到,Python 解释器仅对堆栈的最顶部帧进行操作.Python 使用与调用堆栈分离的另一个堆栈来存储它当前正在执行的帧的局部变量的值.

Note however that frame object's themselves do not store the values of the variables. You see, the Python interpreter only operates on the top-most frame of the stack. Python uses another stack, separate from the call stack, to store the values of the local variables of the frame it's currently executing.

这篇关于引用或复制python递归变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆