“=="和“=="之间有区别吗?和“是"? [英] Is there a difference between "==" and "is"?
问题描述
我的 Google-fu 让我失望了.
在 Python 中,以下两个相等性测试是否等效?
n = 5# 测试一.如果 n == 5:打印耶!"# 测试二.如果 n 是 5:打印耶!"
这是否适用于您将比较实例的对象(例如 list
)?
好的,这样回答了我的问题:
L = []L.append(1)如果 L == [1]:打印耶!"# 成立,但是...如果 L 是 [1]:打印耶!"# 没有.
所以 ==
测试值 where is
测试它们是否是同一个对象?
is
将返回 True
如果两个变量指向同一个对象,==
如果变量引用的对象相等.
在您的情况下,第二个测试仅适用于 Python 缓存小整数对象,这是一个实现细节.对于较大的整数,这不起作用:
<预><代码>>>>1000 是 10**3错误的>>>1000 == 10**3真的同样适用于字符串文字:
<预><代码>>>>一个"是一个"真的>>>"aa" 是 "a" * 2真的>>>x = "a">>>aa"是 x * 2错误的>>>aa"是实习生(x*2)真的请参阅这个问题 也是.
My Google-fu has failed me.
In Python, are the following two tests for equality equivalent?
n = 5
# Test one.
if n == 5:
print 'Yay!'
# Test two.
if n is 5:
print 'Yay!'
Does this hold true for objects where you would be comparing instances (a list
say)?
Okay, so this kind of answers my question:
L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...
if L is [1]:
print 'Yay!'
# Doesn't.
So ==
tests value where is
tests to see if they are the same object?
is
will return True
if two variables point to the same object, ==
if the objects referred to by the variables are equal.
>>> 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
In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
The same holds true for string literals:
>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True
Please see this question as well.
这篇关于“=="和“=="之间有区别吗?和“是"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!