python内置整数对象

标签 python

我读到一篇文章,Python保留了一些数字对象以获得更好的性能。例如:

x = 3
y = 3
print(id(x))
print(id(y))

给出相同的值,这意味着 x 和 y 引用完全相同的对象。文章建议保留的数量对象大约在1~100范围内。

因此我测试了以下代码以获得准确的范围:

for i in range(-1000,1000):
    x = int(str(i))
    y = int(str(i))
    if str(id(x)) == str(id(y)):
        print(i)

结果很奇怪:它打印出-5~256。

我想知道这两个神奇数字是如何产生的以及为什么使用它们。另外,这两个值在不同的环境下会发生变化吗? 谢谢!

最佳答案

256 是 2 的幂,而且足够小,人们会使用该范围内的数字。

-5 我不太确定,也许是特殊值?

相关:What's with the Integer Cache inside Python?

还有来自该线程的智慧之言:

this is an implementation detail, don't ever rely on it happening or not happening

关于python内置整数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39640732/

相关文章:

python - 只选择 Postgresql 的两列并将其存储在 numpy 数组中

python - 属性错误 : module 'builtins' has no attribute 'interpreter'

python - ssh-agent ssh-add ok in user not in sudo

python - 如何在 Windows 上使用 Python 处理包含 EOF/Ctrl-Z 字符的巨大文本文件?

python - 使用 Python 的分数模块找到具有特定分母的最接近小数的分数

Pythonic 对象实例化问题

python - PyQt “Not responding”

python - 如何在Python中的同一个数组中添加不同的元素?

python - 播放带有 winsound 问题的随机 wav 文件

python - UnicodeEncodeError - 在 Spyder 中有效,但从终端执行时无效