了解Python的“是"操作员 [英] Understanding Python's "is" operator
问题描述
is
运算符与变量的值不匹配,但是 实例本身.
The
is
operator does not match the values of the variables, but the instances themselves.
这到底是什么意思?
我声明了两个名为x
和y
的变量,它们在两个变量中都分配了相同的值,但是当我使用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:
运算符
is
和is not
测试对象身份:x is y
当且仅当x
和y
是同一对象时为true.
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object.
改为使用==
运算符:
print(x == y)
这将打印True
. x
和y
是两个单独的列表:
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()
函数,您会看到x
和y
具有不同的标识符:
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屋!