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

2024-05-14 18:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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))

我得到了以下证件:

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?如果这个问题得到了解释,为什么字符串9的ID会发生变化


Tags: 对象字符串代码inidforstringrange
1条回答
网友
1楼 · 发布于 2024-05-14 18:51:24

result_str创建关联的字符串在下一次赋值时到达生存期结束。因此,可能存在重复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.

相关问题 更多 >

    热门问题