繁体   English   中英

Memory Python中嵌套函数的地址

[英]Memory Address of Nested Functions in Python

I have always understood that with nested functions in Python, the declared inner function is created during the enclosing function's invocation, and all the names within the local scope are destroyed when the enclosing function returns.

例如,从这篇 Real Python 文章中

[本地范围] 在 function 调用中创建,而不是在 function 定义中创建,因此您将拥有与 function 调用一样多的不同本地范围。 即使您多次或递归调用相同的 function 也是如此。 每次调用都会创建一个新的本地 scope。

因此,每次调用封闭的 function 都应该为声明的嵌套 function 生成一个新的 memory 地址,对吧?

def normal_function():
    def locally_scoped_function():
        pass

    print(locally_scoped_function)

normal_function() # <function normal_function.<locals>.locally_scoped_function at 0x109867670>
normal_function() # <function normal_function.<locals>.locally_scoped_function at 0x109867670>
normal_function() # <function normal_function.<locals>.locally_scoped_function at 0x109867670>

为什么local_scoped_function的地址是locally_scoped_function 由于每次调用normal_function都应该重新声明和重新创建 function 定义,所以不应该将它存储在 memory 的不同插槽中吗? 我希望打印出来的每一行都有不同的 memory 地址。

似乎我错过了一些非常明显的东西。 我确实尝试在 StackOverflow 上寻找这个,但令人惊讶的是我无法找到关于这个特定问题的答案。

正如@Klaus D. 的评论中所建议的那样 - 当 function 被垃圾收集时,很可能下一个创建的 function 实例将分配在同一地址中。 我们通过一个简单的实验证明这一点

def normal_function():
    def locally_scoped_function():
        pass
    print(locally_scoped_function)
    return locally_scoped_function

# Run as before
for i in range(3):
  normal_function()

# As before, all instances are created at the same address
<function normal_function.<locals>.locally_scoped_function at 0x7f173835f9d8>
<function normal_function.<locals>.locally_scoped_function at 0x7f173835f9d8>
<function normal_function.<locals>.locally_scoped_function at 0x7f173835f9d8>

# Let's save the created instances to avoid garbage collection
collect_to_avoid_gc = []
for i in range(3):
  collect_to_avoid_gc.append(
    normal_function()      
  )

# And indeed we'll see different addresses!
<function normal_function.<locals>.locally_scoped_function at 0x7f1737a32158>
<function normal_function.<locals>.locally_scoped_function at 0x7f1737a32378>
<function normal_function.<locals>.locally_scoped_function at 0x7f1737a32510>

暂无
暂无

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

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