在动态类型中,现有变量的 ID 在 python 中没有改变

In dynamic typing the existing variable's ID isn't changing in python

value = 10

print(value, id(value), type(value))

value = "100"

print(value, id(value), type(value))

输出:

10 1383004224 <class 'int'>
       
100 21775456 <class 'str'>

当我重新运行上面的代码时,TYPE str 的 ID 正在改变,但是 TYPE int 的 ID 没有改变,为什么?

small integer caching Python 缓存小整数,它们是介于 -5 和 256 之间的整数。所以你需要的只是用于你的测试数字大于 256 或小于 -5。

Python 的内置 id() 函数返回的 ID returns 内存地址。

Python 使用缓存(针对不可变类型),如 AskPython 的文章 Using the id() function in Python

中所述

真实 Python 的文章 Small Integer Caching:

中描述了您遇到的(小)整数现象

What is small integer caching? Python caches small integers, which are integers between -5 and 256. These numbers are used so frequently that it’s better for performance to already have these objects available. So these integers will be assigned at startup. Then, each time you refer to one, you’ll be referring to an object that already exists.