Python - comparing long/integer values with == and is [duplicate]

感情迁移 提交于 2019-12-23 08:34:08

问题


Possible Duplicate:
Python “is” operator behaves unexpectedly with integers

Ran into something odd last night where doing

if max_urls is 0:
    max_urls = 10

would always return false... even when max_urls was 0.... it was getting assigned from the database. When I did a

print type(max_urls)

would return

<type 'long'> 0

which seemed right but it would always return false.

If I changed it to

if max_urls == 0:
    max_urls = 10

then finally it would return true when it was 0. Why the difference between == and is?


回答1:


== is a value comparison, is is an object identity (memory location) comparison. You will often see that comparisons like max_urls is 0 will give the intended result because small values are usually cached in Python, but you always want to be using == instead of is when checking equality because this behavior cannot be relied upon.

Here is a brief example illustrating this:

>>> a = 0
>>> (a == 0, a is 0)
(True, True)
>>> a = 1000
>>> (a == 1000, a is 1000)
(True, False)



回答2:


The is operator checks that two references point to the same object. You are testing if long(0) is the same object as int(0), and the answer is no. This will be crystal clear if you print their object ids:

>>> max_urls = long(0)
>>> id(max_urls)
335952
>>> id(0)
8402324

== on the other hand checks that two values are equivalent, even if they are not the exact same object. For instance:

>>> a = 777
>>> b = 777
>>> a is b
False
>>> a == b
True
>>> id(a)
8404568
>>> id(b)
8404640

Note: It is important that I used 777 and not a smaller number like 1 or 2. Quoting from the Python manual:

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.



来源:https://stackoverflow.com/questions/4473673/python-comparing-long-integer-values-with-and-is

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