两个字符串变量被设置为相同的值。s1 == s2总是返回True,但s1 = s2有时返回False。
如果我打开我的Python解释器,并做同样的比较,它成功了:
>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True
为什么会这样?
两个字符串变量被设置为相同的值。s1 == s2总是返回True,但s1 = s2有时返回False。
如果我打开我的Python解释器,并做同样的比较,它成功了:
>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True
为什么会这样?
当前回答
实际上,is操作符检查是否相同,而==操作符检查是否相等。
从语言参考:
Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)
因此,从上面的语句中,我们可以推断出字符串是不可变类型,当使用"is"检查时可能会失败,而当使用"is"检查时可能会成功。
同样适用于int和tuple,它们也是不可变类型。
其他回答
最后需要注意的是,你可以使用sys.intern函数来确保你得到的是同一个字符串的引用:
>>> from sys import intern
>>> a = intern('a')
>>> a2 = intern('a')
>>> a is a2
True
正如在前面的回答中指出的,您不应该使用is来确定字符串的相等性。但这可能有助于了解您是否有一些奇怪的要求使用is。
注意,intern函数曾经是Python 2的内置函数,但在Python 3中被移到了sys模块中。
如果你不确定你在做什么,使用'=='。 如果你对它有更多的了解,你可以用'is'来表示已知的对象,比如'None'。
否则,你最终会想知道为什么事情不管用,为什么会发生这种情况:
>>> a = 1
>>> b = 1
>>> b is a
True
>>> a = 6000
>>> b = 6000
>>> b is a
False
我甚至不确定在不同的Python版本/实现之间是否保证有一些东西保持不变。
根据我有限的Python使用经验,is用于比较两个对象,以确定它们是否是相同的对象,而不是具有相同值的两个不同对象。==用于确定两个值是否相同。
这里有一个很好的例子:
>>> s1 = u'public'
>>> s2 = 'public'
>>> s1 is s2
False
>>> s1 == s2
True
s1是Unicode字符串,s2是普通字符串。它们不是相同的类型,但它们的值相同。
is关键字是测试对象身份,而==是值比较。
如果使用is,当且仅当对象是同一对象时,结果将为真。但是,当对象的值相同时,==将为真。
Is是同一性测试,==是相等性测试。这意味着is是一种检查两件事物是否相同或等价的方法。
假设你有一个简单的person对象。如果它的名字是“Jack”,而且是“23岁”,那么它就相当于另一个23岁的Jack,但它不是同一个人。
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
jack1 = Person('Jack', 23)
jack2 = Person('Jack', 23)
jack1 == jack2 # True
jack1 is jack2 # False
他们年龄相同,但他们不是同一个人。一个字符串可能与另一个字符串等价,但它不是同一个对象。