如何检查两个变量是否在Python中引用了同一对象? [英] How do I check if two variables reference the same object in Python?

查看:203
本文介绍了如何检查两个变量是否在Python中引用了同一对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x和y是两个变量。

我可以使用 x == y 检查它们是否相等,但如何检查是否

x and y are two variables.
I can check if they're equal using x == y, but how can I check if they have the same identity?

示例:

x = [1, 2, 3]
y = [1, 2, 3]

现在 x == y 是True,因为x和y相等,但是x和y不是同一对象。

我正在寻找类似的东西 sameObject(x,y)在这种情况下应该为False。

Now x == y is True because x and y are equal, however, x and y aren't the same object.
I'm looking for something like sameObject(x, y) which in that case is supposed to be False.

推荐答案

您可以使用 is 检查两个对象是否具有相同的对象

You can use is to check if two objects have the same identity.

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y
False

这篇关于如何检查两个变量是否在Python中引用了同一对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆