Python 中的比较方法 is与==的比较

来源:互联网 发布:2016流行网络语 编辑:程序博客网 时间:2024/06/08 07:01

Example:

>>> test4='this is hello world'

>>> test4[8:13]

'hello'

>>> test4[8:13] is 'hello'
False
>>> test4[8:13] == 'hello'
True


例子中is和==都是比较的方法,但'==' 是用来比较两个对象的值是否相同( equality test),类似 'hello'.__eq__(test4[8:13])

但is比较方法是比较两个对象是不是同一个对象( identity test),相当于:

id(test4[8:13]) == id('hello')


而且这里是比较字符串,字符串有个 interned 特性(string interning is a method of storing only one copy of each distinct string value),详情见:

http://en.wikipedia.org/wiki/String_interning


所以当比较非字符串时:

>>> [1, 2] == [1,2]
True
>>> [1, 2] is [1,2]
False


参考资料:

http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce

http://blog.csdn.net/sasoritattoo/article/details/12451359

http://en.wikipedia.org/wiki/String_interning

0 0
原创粉丝点击