Python之False和None

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

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。大体是这样:python

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

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

  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或者为空。this

相关文章
相关标签/搜索