2

I am surprised by the following result, using Python 2.7.4:

>>> id(5)
5068376

>>> id(5)
5068376

When the expression 5 is evaluated, a new object is created with the identity of 5068376. Now, I would expect that repeating the same statement would create another new object, whose identity would be unique, since simply evaluating an expression doesn't yield any references to the object and the object should be garbage collected.

It's not that the interpreter is reusing the same memory address either:

>>> id(6)
5068364

>>> id(5)
5068376

So what gives? Does the interpreter do behind-the-scenes binding of literals?

4

2 回答 2

5

在 Python 中有一系列小数作为单例保存;任何引用都将始终返回相同的对象,并且它们永远不会被垃圾收集。

>>> for x,y in enumerate(range(1000)):
    if x is not y:
        print x,y
        break

257 257
于 2013-04-24T17:44:37.070 回答
3

这里有两件事:

  • 小 Python 整数(从 -5 到 256 包括在内)是interned;文字整数被翻译成相同数字的完全相同的对象。对于这些整数,它们 id()将是常数。

  • 仅在对象的生命周期内id()是唯一的;如果第一个对象已被再次清除,则可以稍后将其重新用于另一个对象。您不会将文字存储在任何地方,因此可以再次重用内存地址:

    >>> id('foo bar')
    4572936304
    >>> id('bar baz')
    4572936304
    

    这里'foo bar''bar baz'是两个不同的对象,但它们的生命周期不重叠。第一个被创建,传递给id()函数,然后再次被销毁。id()然后依次创建、传递和销毁第二个字符串。

于 2013-04-24T17:52:44.313 回答