这个问题在这里已经有了答案:
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/