Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

python - How to create the int 1 at two different memory locations?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...