扫码关注官方订阅号
if foo is None: pass
if foo == None: pass
为什么是两种不同的用法,这两个有什么区别吗?
学习是最好的投资!
is always returns True if it compares the same object instance
is
True
Whereas == is ultimately determined by the __eq__() method
==
__eq__()
>>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False
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 == b True >>> a is b False
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.
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
isalways returnsTrueif it compares the same object instanceWhereas
==is ultimately determined by the__eq__()methodPython中变量本身不存储其值,变量赋值事实上是将变量引用指向内存中缓存的对象本身,比如:
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值相等”
对楼上所述,进行一点补充。
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.