python recursive variables referenced or copied?

≯℡__Kan透↙ 提交于 2019-12-23 12:24:46

问题


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

回答1:


The underlining concept your looking for is called a frame.

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.

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.

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.



来源:https://stackoverflow.com/questions/46589881/python-recursive-variables-referenced-or-copied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!