Confused about Python’s id() [duplicate]

2020-01-28 13:21发布

I can understand the following definition:

Every object has an identity, a type and a value. An object's identity never changes once it has been created; you may think of it as the object’s address in memory. The is operator compares the identity of two objects; the id() function returns an integer representing its identity.

I would assume the above definition works when “something” is created, such as:

>>> a = 0
>>> id(a)
1720438480

But I do not understand:

>>> id(1)
1720438512
>>> b = 1
>>> id(b)
1720438512

I did not create anything yet; so how can the integer “1” have an ID? Does it mean that as soon as I “mention” 1 in the Python Shell, it is assigned to a memory address? Also, does it mean that because the ID never changes during its lifetime, and because my computer has a limited memory, if I repeatedly ask for the id() of unique things, I will eventually get something like “out of memory” message? (It cannot reallocate memory, because the lifetime of others have not ended yet.)

Or, showing my ear from the other way round:

>>> id(something_1)
some unique memory address
>>> id(something_2)
some unique memory address
>>> ...

At which point is the memory reallocated? That is, at which point,

>>> my_variable = something_1
>>> id(my_variable)

will give an ID that is different from id(something_1)?

1条回答
家丑人穷心不美
2楼-- · 2020-01-28 13:47

In general, as soon as you use an integer or a string or any other literal, Python creates a new object in memory for you. It is guaranteed to have the same id for the lifetime of the object, that is, while its reference count is not zero.

When you write something like:

>>> id(1000)
140497411829680

Python creates the integer 1000 and returns its id (the memory address of the object in CPython). After this is done, the reference count of the integer object 1000 is zero and it is deleted. This ensures that you cannot keep filling memory just by writing id(something) (and not binding any variable name to the object).

Typically, you cannot predict when reuse will happen, but in my Python shell it happens quite consistently:

>>> id(1000)
140697307078576
>>> id(1001)
140697307078576
>>> id(1002)
140697307078576
>>> id(1003)
140697307078576

You can see that the same memory address get used again and again when each new integer is created. However, if you prevent the reference count from dropping to zero, you can see that new memory is used instead:

>>> a = 1000
>>> id(a)
140697307078576
>>> b = 1001
>>> id(b)
140697306008368

In CPython, the integers -5 through to 255 are special cases in that they always exist (and so always have the same id during a Python runtime). This is an optimisation to avoid repeated creation and destruction of commonly-used integers.

查看更多
登录 后发表回答