了解Python的“是"操作员 [英] Understanding Python's "is" operator

查看:114
本文介绍了了解Python的“是"操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

is运算符与变量的值不匹配,但是 实例本身.

The is operator does not match the values of the variables, but the instances themselves.

这到底是什么意思?

我声明了两个名为xy的变量,它们在两个变量中都分配了相同的值,但是当我使用is运算符时,它返回false.

I declared two variables named x and y assigning the same values in both variables, but it returns false when I use the is operator.

我需要澄清.这是我的代码.

I need a clarification. Here is my code.

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

print(x is y)  # It prints false!

推荐答案

您误解了is运算符的测试内容.它测试两个变量是否指向同一对象,而不是两个变量具有相同的值.

You misunderstood what the is operator tests. It tests if two variables point the same object, not if two variables have the same value.

is运算符的文档中:

From the documentation for the is operator:

运算符isis not测试对象身份:x is y当且仅当xy是同一对象时为true.

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

改为使用==运算符:

print(x == y)

这将打印True. xy是两个单独的列表:

This prints True. x and y are two separate lists:

x[0] = 4
print(y)  # prints [1, 2, 3]
print(x == y)   # prints False

如果使用 id()函数,您会看到xy具有不同的标识符:

If you use the id() function you'll see that x and y have different identifiers:

>>> id(x)
4401064560
>>> id(y)
4401098192

,但是如果要将y分配给x,则两者都指向同一个对象:

but if you were to assign y to x then both point to the same object:

>>> x = y
>>> id(x)
4401064560
>>> id(y)
4401064560
>>> x is y
True

is显示两者都是同一对象,它返回True.

and is shows both are the same object, it returns True.

请记住,在Python中,名称只是引用值的标签;您可以有多个名称指向同一个对象. is告诉您两个名称是否指向一个相同的对象. ==告诉您两个名称是否引用具有相同值的对象.

Remember that in Python, names are just labels referencing values; you can have multiple names point to the same object. is tells you if two names point to one and the same object. == tells you if two names refer to objects that have the same value.

这篇关于了解Python的“是"操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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