简体   繁体   English

Python object 识别(缓存)在交互 window 和使用 id() 命令时的脚本执行时不同?

[英]Python object identification (caching) different in the interactive window and script execution when using id() command?

I know Python has a cache for objects with numerical values between -5 and 256. I can confirm this in Python interactive window (console).我知道 Python 对数值介于 -5 和 256 之间的对象有一个缓存。我可以在 Python 交互式 window(控制台)中确认这一点。 For example,例如,

a = -10
b = -10
print(id(a))
1797396904912
print(id(b))
1797396904976
print(id(a) == id(b))
False

However, when I run exactly the same code via a script:但是,当我通过脚本运行完全相同的代码时:

a = -10
b = -10
print(id(a))
print(id(b))
print(id(a) == id(b))

I get:我得到:

1797396904848
1797396904848
True

What's going on?这是怎么回事? (The question has nothing to do with another question on id of strings with and without a space). (这个问题与另一个关于带和不带空格的字符串 id 的问题无关)。

No one seems to have an answer.似乎没有人有答案。 I did a bit more exploration and found out that the problem exists in Anaconda but not in IDLE for a = -10 and b = -10.我做了更多的探索,发现问题存在于 Anaconda 中,但在 IDLE 中不存在 a = -10 和 b = -10。

However, the problem exists for c = 257 and d = 257. Different id(c) and id(d) when running in the interactive window.但是,c = 257 和 d = 257 存在问题。在交互式 window 中运行时,id(c) 和 id(d) 不同。 Same id(c) and id(d) when running IDLE script.运行 IDLE 脚本时相同的 id(c) 和 id(d)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM