1 回答

TA貢獻1942條經(jīng)驗 獲得超3個贊
Python的文檔在id()
中有這樣一句話:
Return the ``identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)
里面說,兩個生存期不重疊的對象有可能有相同的id()
值,正如你在C里面malloc()
之后立刻free()
,然后又分配,兩次的內(nèi)存極有可能是相同的。在你的print id(float('inf')), id(float('-inf'))
中生存期并沒有重疊,因為在id()
返回了它的id之后float('inf')
就因為不再被引用而被釋放了,生存期結(jié)束;而后下一個float('-inf')
就被Python分配了相同的id。這里要補充,這里id是否相同是實現(xiàn)相關(guān)的,也就是說,可能CPython會相同,而JPython未必,IronPython也未必。
當然了,等號在判斷float
是否相等的時候,是不關(guān)心它的id,只關(guān)心它的值。==
在關(guān)心id的情況,只有在比較類的實例的時候,int, float, str, list, dict
依然是判斷值:
>>> class C:
... pass
...
>>> a = C()
>>> b = C()
>>> a == b
False
然而整數(shù)又是不同的狀況,這時為什么呢?這時因為Python有一個small_int
緩存(有多小呢,CPython 2.7的實現(xiàn)是規(guī)定在[-5, 256]
),它將小整數(shù)緩存起來,每次引用到這個整數(shù)就從緩存里拿對象,從而避免頻繁內(nèi)存分配,于是就造成了這個著名的情況:
>>> a = 1
>>> id(a)
33739096
>>> b = 1
>>> id(b)
33739096
>>> b = 2
>>> id(b)
33739072
>>> a += 1
>>> id(a)
33739072
添加回答
舉報