问题
I want to show someone how using is
instead of ==
to compare integers can fail. I thought this would work, but it didn't:
>>> import copy
>>> x = 1
>>> y = copy.deepcopy(x)
>>> x is y
True
I can do this easily for bigger integers:
>>> x = 500
>>> y = 500
>>> x is y
False
How can I demonstrate the same thing with smaller integers which might typically be used for enum-like purposes in python?
回答1:
The following example fails in both Python 2 and 3:
>>> n=12345
>>> ((n**8)+1) % (n**4) is 1
False
>>> ((n**8)+1) % (n**4) == 1
True
The reasons are slightly different. Python 2 uses the int
type for small integers and the long
type for arbitrary precision values. Only the int
type is interned so the example fails when a 1L
is returned.
Python 3 only uses the arbitrary precision type (and renamed it to int
). The example fails because the remainder calculation internally computes a value of 1 and returns it. The interning check is only done when objects are created and the object was created at the start of the calculation before it had the value 1.
回答2:
You can do:
>>> 0 - 6 is -6
False
>>> 0 - 6 == -6
True
It also works for bigger numbers:
>>> 1000 + 1 is 1001
False
>>> 1000 + 1 == 1001
True
It depends on what you want to demonstrate but the above highlights the difference in functionality between is
and ==
.
回答3:
What you observe is expected:
>>> x=256
>>> y=256
>>> x is y
True
>>> x=257
>>> y=257
>>> x is y
False
>>> x=-5
>>> y=-5
>>> x is y
True
>>> x=-6
>>> y=-6
>>> x is y
False
Quoting from Plain Integer Objects:
The current implementation keeps an array of integer objects for all integers between
-5
and256
, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of1
. I suspect the behaviour of Python in this case is undefined. :-)
来源:https://stackoverflow.com/questions/21456318/how-to-create-the-int-1-at-two-different-memory-locations