Python中is和==有什么区别?,pythonis,if foo is No


if foo is None: pass
if foo == None: pass

为什么是两种不同的用法,这两个有什么区别吗?

is always returns True if it compares the same object instance

Whereas == is ultimately determined by the __eq__() method

>>> class foo(object):def __eq__(self, other):    return True>>> f = foo()>>> f == NoneTrue>>> f is NoneFalse

Python中变量本身不存储其值,变量赋值事实上是将变量引用指向内存中缓存的对象本身,比如:
a=5
b=5
看似两个变量实际指向同一个对象,此时a==b,a is b都为True,==操作符比较两个对象的值,is 则判断两个变量是否指向同一个引用,想判断是否同一对象,用函数id()即可显示出实际对象的标识(一个整数),此时id(a),id(b),id(5)的标识符都是一致的。
同理,如果foo为None时,事实上是将foo指向None对象的实际标识符,此时用id()显示任何为None的变量的标识,会发现与id(None)的结果相同。
题目中的结果一样,但语义不同,就看你是想表达“foo与None为同一对象”,还是“foo值与None值相等”

对楼上所述,进行一点补充。

>>> a = [1,2,3,4,5]>>> b = [1,2,3,4,5]>>> id(a)3074840940L>>> id(b)3074840972L>>> a == bTrue>>> a is bFalse

Plz ask before google. http://jaredgrubb.blogspot.com/2009/04/python-is-none-vs-none.html , this link may help u to understand it. The author think there is no big difference between them.

编橙之家文章,

评论关闭