我的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.
所以==测试值测试是看他们是否相同的对象?
如果两个变量指向同一个对象(在内存中),则返回True,如果变量引用的对象相等则返回==。
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
# Make a new copy of list `a` via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True
在您的情况下,第二个测试只能工作,因为Python缓存小整数对象,这是一个实现细节。对于较大的整数,这行不通:
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
这同样适用于字符串字面量:
>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True
请看这个问题。