开发者

identifying objects, why does the returned value from id(...) change?

id(object)

This is an integer (or long integer) which is开发者_开发技巧 guaranteed to be unique and constant for this object during its lifetime.

Can you explain this output? Why does j's id change?

>>> i=10  
>>> id(i)  
6337824  
>>> j=10  
>>> id(j)  
6337824  
>>> j=j+1  
>>> id(j)  
6337800  
>>> id(i)  
6337824  


Because integers are immutable, each integer value is a distinct object with a unique id. The integer 10 has a different id from 11. Doing j=j+1 doesn't change the value of an existing integer object, rather it changes j to point to the object for 11.

Check out what happens when we independently create a new variable k and assign it the value 11:

>>> j=10
>>> id(j)
8402204
>>> j=j+1
>>> id(j)
8402192
>>> k=11
>>> id(k)
8402192

Note that it is not always the case that every integer has one and only one corresponding object. This only happens for small integers that Python decides to cache. It does not happen for large integers:

>>> x = 123456789
>>> id(x)
8404568
>>> y = 123456789
>>> id(y)
8404604

See https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.


This is why 2**8 is 2**8 == True, and 2**9 is 2**9 == False.

Values between -5 and 256 are preallocated.


The same id for different variables is a product of how Python creates variables.

id is a hash of the the location of an object in memory. Python variables are references to an object, not new objects. If several variables reference the same object, they have the same `id.


In CPython, id is generally derived from the Py_Object's pointer value, that is its location in memory.


Python caches immutable objects(read integers and tuples..) - which is why they are immutable and saves memory if u reference the same immutable in many places. So small integers, empty tuples and such are actually cached in Python runtime, so you keep getting back the same object and hence the same id.

Try this for the list, you don't get the same id.


These are primitive types, so I'm guessing each value gets its own ID. Try creating a true object and I think you'll see the functionality you expect.

If you need an id for a primitive, you could create an object with just one member of that type.


j's id changes because the object named by j changes. First you initialize j to 10, so when you call id(j) you get the id of 10. Then you set j to 11, so after that when you call id(j) you get the id of 11.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜