Python中的'is'关键字和JS中的===关键字一样吗?

Is the 'is' keyword in Python the same as the === keyword in JS?

我看到了这个问题here,现在我很好奇。与 JS 中的 === 符号相比,is 运算符在 python 中的行为如何?

不,它们不一样。 is in Python 检查两个对象在 Python 中是否具有相同的 id,即。它们是相同的,即使在记忆中也是如此。您可以做的检查是:

>>> a='foo'
>>> a is 'foo'
True
>>> id(a)
44434088
>>> id('foo')
44434088
>>> a=[1]
>>> a is [1]
False
>>> id(a)
45789792
>>> id([1])
4469824

在 Javascript 中,== 运算符在比较相等性时将进行隐式类型转换,例如,[] == "" 将 return true=== 运算符用于在不进行类型转换的情况下检查相等性([] === "" returns false.)

在 Python 中,is 关键字检查引用相等性。因此,如果 xy 都指向内存中的同一个对象,x is y 只会 return 为真。例如:

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

可能由此产生的一些陷阱是建议的空值检查,x is NoneNone 在内存中总是指向同一个 space,所以你可以放心,如果 x 有一个 None 值(否则为 False)。

您可能还会遇到一些怪癖,例如:

x = 1
y = 1
x is y # True

以上是 CPython(您可能正在使用的 Python 解释器)中非标准行为的结果,其中小整数在程序启动时全部分配给特定对象向上。您可以检查这是否不适用于更大的数字:

x = 1000
y = 1000
x is y # False

除非您正在检查 None 或者您特别想确保两个变量指向内存中的同一位置,否则您应该使用 == 而不是 is .

没有。 Python 中的 is 似乎比 JS 中的 === 严格

在 JS 中:

For value types (numbers): a === b returns true if a and b have the same value and are of the same type

For reference types: a === b returns true if a and b reference the exact same object

For strings: a === b returns true if a and b are both strings and contain the exact same characters


在Python中:

没有矛盾,除了id(obj1)id(obj2)相同,两个对象不相同,obj1 is obj2将计算为False