Python之False和None

这个其实在Python文档当中有写了,为了准确起见,我们先引用Python文档当中的原文:

In the context of Boolean operations, and also when expressions are used bycontrol flow statements, the following values are interpreted as false:False, None, numeric zero of all types, and empty strings and containers(including strings, tuples, lists, dictionaries, sets and frozensets). Allother values are interpreted as true. (See the __nonzero__()special method for a way to change this.)


进行逻辑判断(比如if)时,Python当中等于False的值并不只有False一个,它也有一套规则。对于基本类型来说,基本上每个类型都存在一个值会被判定为False。大致是这样:

  1. 布尔型,False表示False,其他为True
  2. 整数和浮点数,0表示False,其他为True
  3. 字符串和类字符串类型(包括bytes和unicode),空字符串表示False,其他为True
  4. 序列类型(包括tuple,list,dict,set等),空表示False,非空表示True
  5. None永远表示False

自定义类型则服从下面的规则:

  1. 如果定义了__nonzero__()方法,会调用这个方法,并按照返回值判断这个对象等价于True还是False
  2. 如果没有定义__nonzero__方法但定义了__len__方法,会调用__len__方法,当返回0时为False,否则为True(这样就跟内置类型为空时对应False相同了)
  3. 如果都没有定义,所有的对象都是True,只有None对应False

所以回到问题,not None的确会返回True。不过一定要警惕的是,if a is None和if a,if a is not None和if not a不可以随便混用,前面也说过了,它们在很多时候是不同的,比如说当a是一个列表的时候if not a其实是判断a为None或者为空。

原文地址:https://www.cnblogs.com/zhangyafei/p/9930178.html