“是"即使两个对象具有相同的ID,操作也会返回false [英] "is" operation returns false even though two objects have same id
问题描述
两个python对象具有相同的id,但"is"操作返回false,如下所示:
Two python objects have the same id but "is" operation returns false as shown below:
a = np.arange(12).reshape(2, -1)
c = a.reshape(12, 1)
print("id(c.data)", id(c.data))
print("id(a.data)", id(a.data))
print(c.data is a.data)
print(id(c.data) == id(a.data))
这是实际输出:
id(c.data) 241233112
id(a.data) 241233112
False
True
我的问题是...为什么"c.data是a.data"即使它们指向相同的ID也指向相同的对象,却返回false?我以为如果它们具有相同的ID,则它们指向相同的对象,或者我错了吗?谢谢!
My question is... why "c.data is a.data" returns false even though they point to the same ID, thus pointing to the same object? I thought that they point to the same object if they have same ID or am I wrong? Thank you!
推荐答案
a.data
和c.data
都产生一个 transient 对象,但没有对其进行引用.这样,两者都会立即被垃圾收集.两者可以使用相同的ID.
a.data
and c.data
both produce a transient object, with no reference to it. As such, both are immediately garbage-collected. The same id can be used for both.
在您的第一个if
语句中,对象必须共存,而is
检查它们是否相同.
In your first if
statement, the objects have to co-exist while is
checks if they are identical, which they are not.
在第二个if
语句中,每个对象都在id
返回其ID后立即释放.
In the second if
statement, each object is released as soon as id
returns its id.
如果保存对两个对象的引用,并使它们保持活动状态,则可以看到它们不是同一对象.
If you save references to both objects, keeping them alive, you can see they are not the same object.
r0 = a.data
r1 = c.data
assert r0 is not r1
这篇关于“是"即使两个对象具有相同的ID,操作也会返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!