理解 Python 的“是"操作员 [英] Understanding Python's "is" operator
问题描述
is
运算符不匹配变量的值,但是实例本身.
这到底是什么意思?
我声明了两个名为 x
和 y
的变量,在这两个变量中分配了相同的值,但是当我使用 is
运算符时它返回 false.
我需要澄清一下.这是我的代码.
x = [1, 2, 3]y = [1, 2, 3]print(x is y) # 打印错误!
您误解了 是什么
运算符测试.它测试两个变量是否指向同一个对象,而不是两个变量是否具有相同的值.
来自 is
运算符的文档:
运算符 is
和 isnot
测试对象身份:x is y
为真当且仅当 x
和 y
是同一个对象.
改用 ==
运算符:
print(x == y)
这会打印 True
.x
和 y
是两个单独的列表:
x[0] = 4print(y) # 打印 [1, 2, 3]打印(x == y)#打印假
如果您使用 id()
函数 你会看到 x
和 y
有不同的标识符:
但是如果你把 y
赋值给 x
那么它们都指向同一个对象:
和is
表明两者是同一个对象,返回True
.
请记住,在 Python 中,名称只是引用值的标签;您可以有多个名称指向同一个对象.is
告诉您两个名称是否指向同一个对象.==
告诉您两个名称是否引用具有相同值的对象.
The
is
operator does not match the values of the variables, but the instances themselves.
What does it really mean?
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!
You misunderstood what the is
operator tests. It tests if two variables point the same object, not if two variables have the same value.
From the documentation for the is
operator:
The operators
is
andis not
test for object identity:x is y
is true if and only ifx
andy
are the same object.
Use the ==
operator instead:
print(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
If you use the id()
function you'll see that x
and y
have different identifiers:
>>> id(x)
4401064560
>>> id(y)
4401098192
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
and is
shows both are the same object, it returns True
.
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屋!