代码中经常会有变量是否为None的判断,有三种主要的写法:
第一种是if x is None;
第二种是 if not x:;
第三种是if not x is None(这句这样理解更清晰if not (x is None)) 。
如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:
1>>> x = 1 2>>> not x 3False 4>>> x = [1] 5>>> not x 6False 7>>> x = 0 8>>> not x 9True 10>>> x = [0] # You don't want to fall in this one. 11>>> not x 12False
在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False ,即:
not None == not False == not '' == not 0 == not [] == not {} == not ()
因此在使用列表的时候,如果你想区分x==[]和x==None两种情况的话, 此时if not x:将会出现问题:
1>>> x = [] 2>>> y = None 3>>> 4>>> x is None 5False 6>>> y is None 7True 8>>> 9>>> 10>>> not x 11True 12>>> not y 13True 14>>> 15>>> 16>>> not x is None 17>>> True 18>>> not y is None 19False 20>>>
也许你是想判断x是否为None,但是却把x==[]的情况也判断进来了,此种情况下将无法区分。
对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
而对于if x is not None和if not x is None写法,很明显前者更清晰,而后者有可能使读者误解为if (not x) is None,因此推荐前者,同时这也是谷歌推荐的风格
结论:
if x is not None是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。
使用if not x这种写法的前提是:必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
================================================================
不过这并不适用于变量是函数的情况,以下转载自:https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md foo is None 和 foo == None的区别
问题 链接
1if foo is None: pass 2if foo == None: pass
如果比较相同的对象实例,is总是返回True 而 == 最终取决于 "eq()"
1>>> class foo(object): 2 def __eq__(self, other): 3 return True 4 5>>> f = foo() 6>>> f == None 7True 8>>> f is None 9False 10 11>>> list1 = [1, 2, 3] 12>>> list2 = [1, 2, 3] 13>>> list1==list2 14True 15>>> list1 is list2 16False
另外
(ob1 is ob2) 等价于 (id(ob1) == id(ob2))
################################################################################
补充,2013.10.09
转自http://zhidao.baidu.com/question/514056244.html
python中的not具体表示是什么,举个例子说一下,衷心的感谢
1 在python中not是逻辑判断词,用于布尔型True和False,not True为False,not False为True,以下是几个常用的not的用法: 2(1) not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句。比如: 3a = False 4if not a: (这里因为a是False,所以not a就是True) 5 print "hello" 6这里就能够输出结果hello 7 8None=False=''=0=[]={}=() 9 10(2) 判断元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,这句话的意思是如果a不在列表b中,那么就执行冒号后面的语句,比如: 11a = 5 12b = [1, 2, 3] 13if a not in b: 14 print "hello" 15这里也能够输出结果hello
not x 意思相当于 if x is false, then True, else False ———————————————— 版权声明:本文为CSDN博主「跟随内心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/sasoritattoo/article/details/12451359
