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

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

问题描述

<块引用>

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

这到底是什么意思?

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

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

x = [1, 2, 3]y = [1, 2, 3]print(x is y) # 打印错误!

解决方案

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

来自 is 运算符的文档:

<块引用>

运算符 isisnot 测试对象身份:x is y 为真当且仅当 xy 是同一个对象.

改用 == 运算符:

print(x == y)

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

x[0] = 4print(y) # 打印 [1, 2, 3]打印(x == y)#打印假

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

<预><代码>>>>编号(x)4401064560>>>编号(y)4401098192

但是如果你把 y 赋值给 x 那么它们都指向同一个对象:

<预><代码>>>>x = y>>>编号(x)4401064560>>>编号(y)4401064560>>>x 是 y真的

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 and is not test for object identity: x is y is true if and only if x and y 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屋!

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