python代码 if not x: 和 if x is not None: 和 if not x is Non
代码中经常会有变量是否为None的判断,有三种主要的写法: gt;gt;gt; x = 1 gt;gt;gt; not x False gt;gt;gt; x = [1] gt;gt;gt; not x False gt;gt;gt; x = 0 gt;gt;gt; not x True gt;gt;gt; x = [0] # You don't want to fall in this one. gt;gt;gt; not x False 在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False ,即: 复制代码 代码如下: 因此在使用列表的时候,如果你想区分x==[]和x==None两种情况的话, 此时`if not x:`将会出现问题: gt;gt;gt; x = [] gt;gt;gt; y = None gt;gt;gt; gt;gt;gt; x is None False gt;gt;gt; y is None True gt;gt;gt; gt;gt;gt; gt;gt;gt; not x True gt;gt;gt; not y True gt;gt;gt; gt;gt;gt; gt;gt;gt; not x is None gt;gt;gt; True gt;gt;gt; not y is None False gt;gt;gt; 也许你是想判断x是否为None,但是却把`x==[]`的情况也判断进来了,此种情况下将无法区分。 结论: ================================================================ foo is None 和 foo == None的区别 问题 链接 if foo is None: pass 如果比较相同的对象实例,is总是返回True 而 == 最终取决于 "eq()" gt;gt;gt; class foo(object): def __eq__(self, other): return True gt;gt;gt; f = foo() gt;gt;gt; f == None True gt;gt;gt; f is None False gt;gt;gt; list1 = [1, 2, 3] gt;gt;gt; list2 = [1, 2, 3] gt;gt;gt; list1==list2 True gt;gt;gt; list1 is list2 False 另外 (ob1 is ob2) 等价于 (id(ob1) == id(ob2)) ################################################################################ python中的not具体表示是什么,举个例子说一下,衷心的感谢 在python中not是逻辑判断词,用于布尔型True和False,not True为False,not False为True,以下是几个常用的not的用法: not x 意思相当于 if x is false, then True, else False (编辑:淮北站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |