我的Google-fu让我失望了

在Python中,以下两个相等测试是否等效?

n = 5
# Test one.
if n == 5:
    print 'Yay!'

# Test two.
if n is 5:
    print 'Yay!'

这是否适用于对象,你将比较实例(一个列表说)?

这就回答了我的问题

L = []
L.append(1)
if L == [1]:
    print 'Yay!'
# Holds true, but...

if L is [1]:
    print 'Yay!'
# Doesn't.

所以==测试值测试是看他们是否相同的对象?


当前回答

你的答案是正确的。is操作符比较两个对象的标识符。==操作符比较两个对象的值。

对象的标识一旦创建就不会改变;你可以把它看作是对象在内存中的地址。

你可以通过定义__cmp__方法或像__eq__这样的富比较方法来控制对象值的比较行为。

其他回答

==确定值是否相等,而is确定它们是否完全相同的对象。

由于这篇文章中的其他人详细回答了==和is之间的区别,用于比较对象或变量,我将主要强调is和==之间的比较,用于字符串,可以给出不同的结果,我将敦促程序员谨慎使用它们。

对于字符串比较,确保使用==而不是is:

str = 'hello'
if (str is 'hello'):
    print ('str is hello')
if (str == 'hello'):
    print ('str == hello')

Out:

str is hello
str == hello

但是在下面的例子中== and is会得到不同的结果:

str2 = 'hello sam'
    if (str2 is 'hello sam'):
        print ('str2 is hello sam')
    if (str2 == 'hello sam'):
        print ('str2 == hello sam')

Out:

str2 == hello sam

结论与分析:

使用的是仔细比较之间的字符串。 因为是用来比较对象的,而且在Python 3+中,每个变量(如字符串)都被解释为对象,让我们看看上面的段落中发生了什么。

在python中,有一个id函数,它显示一个对象在其生命周期内的唯一常数。这个id在Python解释器的后端使用is关键字来比较两个对象。

str = 'hello'
id('hello')
> 140039832615152
id(str)
> 140039832615152

But

str2 = 'hello sam'
id('hello sam')
> 140039832615536
id(str2)
> 140039832615792

https://docs.python.org/library/stdtypes.html#comparisons

是身份测试 ==测试是否相等

每一个(小的)整数值都被映射到一个单独的值,所以每3都是相同的。这是一个实现细节,但不是语言规范的一部分

简而言之,is检查两个引用是否指向同一个对象。==检查两个对象是否具有相同的值。

a=[1,2,3]
b=a        #a and b point to the same object
c=list(a)  #c points to different object 

if a==b:
    print('#')   #output:#
if a is b:
    print('##')  #output:## 
if a==c:
    print('###') #output:## 
if a is c:
    print('####') #no output as c and a point to different object 

看看Stack Overflow问题Python的“is”运算符对整数的行为出人意料。

它主要归结为“is”检查它们是否是相同的对象,而不仅仅是彼此相等(256以下的数字是一个特殊情况)。