我开始知道python中的任何对象都有相同的id,而与它所使用的位置无关。由replace()返回的字符串和相同的字符串在Python中有不同的id?
a=5
print id(5)==id(a)
此声明打印为真。
a='hillo'
b='hello'
c=b.replace('e','i') #this gives c='hillo'
print id(a)==id(c)
此声明打印False
。但为什么?
我开始知道python中的任何对象都有相同的id,而与它所使用的位置无关。由replace()返回的字符串和相同的字符串在Python中有不同的id?
a=5
print id(5)==id(a)
此声明打印为真。
a='hillo'
b='hello'
c=b.replace('e','i') #this gives c='hillo'
print id(a)==id(c)
此声明打印False
。但为什么?
我开始知道python中的任何对象都有相同的id,而与它所使用的位置无关。
该陈述是完全错误的。
小整数的ID根据它们的不变值和程序中的第一次出现,因为它们的值很小,并且Python会缓存它们。这就是为什么你的第一个例子返回True
。
然而,在你的第二个例子,你在比较两个不同(immutable)的字符串的ID,这就是为什么它返回False
。一般来说,一个新的String(literal)实例每次都会创建一个新的String对象,因此创建一个不同的ID。
感谢编辑@FerdinandBeyer。 –
由于字符串在Python中,方法replace()将字符串的一个副本返回到另一个地址,在该地址中old被替换为new。这就是为什么有两个不同的ID。另一个类似的情况:
>>> p = "ooo"
>>> q = "ooovooo"
>>> r = p + "vooo"
>>> r
'ooovooo'
>>> q
'ooovooo'
>>> id(q) == id(r)
False
Python为p和“vooo”的连接处指定新地址。这就是为什么这两个字符串都不一样
_I知道python中的任何对象都具有相同的id,而不管它使用的位置如何。 –
阅读此https://docs.python.org/3.5/reference/datamodel.html#data-model – RaminNietzsche
[Python中的两个变量具有相同的id,但不包含列表或元组](https:// stackoverflow。 com/questions/38189660/python-two-variables-have-same-id-but-not-lists-or-tuples) – RaminNietzsche