“is” and “id” in Python 3.5 [duplicate]

眉间皱痕 提交于 2020-01-07 01:49:27

问题


i have questions: I'm using python 3.5 , win7-32bit system.

Here's my code:

a=3
b=3
print(id(a))
print(id(b))

it returns:

1678268160
1678268160

So we could know that a and b reference to same object.

But here comes the question:

a=3
b=3
print( id(a) is id(b) )

It return :

False

I dont understand why this happened, I think it should be True. Can anyone explain to me? Thanks !


回答1:


id returns a Python int object (the memory address of the object you're id-ing, though that's an implementation detail). But aside from very small ints (again, implementation detail), there is no int caching in Python; if you compute the same int two ways, it's two different int objects that happen to have the same value. Similarly, a fresh int is created on each call to id, even if the objects are the same.

The equivalence for id and is is that a is b implies id(a) == id(b), not id(a) is id(b) (and in fact, since ids are large numbers, id(a) is id(b) is almost always False).

Also note, your test case is flawed in other ways:

a = 3
b = 3
a is b

only returns True for the is comparison because of the small int cache in CPython; if you'd done:

a = 1000
b = 1000
a is b

a is b would be False; your assumptions about identity only hold in CPython for numbers in the range -5 to 256 inclusive, which are singletons for performance reasons, but all other ints are recreated as needed, not singletons.




回答2:


id(a) is id(b) compares the ids of the ids returned by the id function.

id(a) == id(b) will be True since the a is b and during an object's lifetime, the value returned by id will always be the same. However, each time id is called, a distinct integer (that has the same value) is returned so id(a) is id(b) is False.



来源:https://stackoverflow.com/questions/36026537/is-and-id-in-python-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!