python - 为什么不同的字符串在 Python 中具有相同的 ID?

标签 python

这个问题在这里已经有了答案:





How unique is Python's id()?

(3 个回答)


去年关闭。




据说字符串是不可变的对象,当我们对该变量进行更改时,它实际上会创建一个新的字符串对象。

所以我想用这段代码来测试这个现象:

result_str = ""

print("string 1 (unedited):", id(result_str))

for a in range(1,11):
    result_str = result_str + str(a)
    print(f"string {a+1}:", id(result_str))

我得到了以下 ID:
string 1 (unedited): 2386354993840
string 2: 2386357170336
string 3: 2386357170336
string 4: 2386357170336
string 5: 2386357170336
string 6: 2386357170336
string 7: 2386357170336
string 8: 2386357170336
string 9: 2386360410800
string 10: 2386360410800
string 11: 2386360410800

那么,如果每个字符串彼此不同,那么为什么字符串 2-8 和 9-11 具有相同的 ID?而且,如果以某种方式解释了这个问题,为什么 ID 会在字符串 9 处发生变化?

最佳答案

您与 result_str 关联的字符串create 在下一次分配时到达生命周期结束。因此有可能出现重复的 id。

这是doc

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

关于python - 为什么不同的字符串在 Python 中具有相同的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62453270/

相关文章:

python - deepcopy的第二个参数memo的作用是什么?

java - 将字符串解释为打包的二进制数据,Python 与 Java

python - 在 Pandas 中选择感兴趣的行之前和之后的行

python - python 中的 input() 和\n 字符

python - 如何让 Pylance 理解 Pydantic 的 `allow_population_by_field_name` 初始化器?

python - 如何添加一个计数器来跟踪 while 循环中的月份和年份?

python - 在 Python 中使用 Selenium 上传文件

python - 使用 Pandas 将 csv 转换为 Json

python - 交互式经纪人 : How to retrieve transaction history records?

python - python中的mongo查询