1

我遇到的一个 Python 教程提到每次调用封闭函数时都会创建本地函数的新实例。

我尝试通过以下两个示例对其进行测试:

示例 1:我object id从本地函数中获取本地函数,为每个函数调用创建新实例。这项工作符合预期。

    >>> def outer():
    ...  def inner():  
    ...   print(inner)
    ...  inner()
    ... 
    >>> outer()
    <function outer.<locals>.inner at 0x7f7b143bd620>
    >>> outer()
    <function outer.<locals>.inner at 0x7f7b143bd6a8>

示例 2:但是当object id从外部函数中获取局部函数时,Python 似乎不会为每次调用外部函数创建局部函数的新实例。

>>> def outer2():
...  def inner2():
...   pass   
...  print(inner2)
...  inner2()
... 
>>> outer2()
<function outer2.<locals>.inner2 at 0x7f7b143bd7b8>
>>> outer2()
<function outer2.<locals>.inner2 at 0x7f7b143bd7b8>

谁能指出这里发生了什么?

我明白:

The id of an object is only guaranteed to be unique during that object's 
lifetime, not over the entire lifetime of a program.

我的问题是:

为什么这两个示例的行为不同,尽管在这两种情况下,执行 print 语句后对象都不再存在。

4

0 回答 0