器→工具, 术→技巧, 研发, 编程语言

Python 逻辑判断True/False的坑

钱魏Way · · 7,003 次浏览

Python中的True和False的定义,在不同版本的Python中是这样定义的:

  • Python 2:None, 0, 和空字符串都被算作 False,其他的均为 True
  • Python 3:None,0,空字符串,空列表,空字典都算是False,所有其他值都是True

但在实际使用中,上述的定义和实际表现不一致。比如如下测试:

以下为在Python 3  坏境下的测试:

>>> bool(0)
False
>>> bool("")
False
>>> bool([])
False
>>> bool({})
False
>>> bool(None)
False

如果使用==测试,则结果为:

>>> 0 == False
True
>>> "" == False
False
>>> [] == False
False
>>> {} == False
False
>>> None == False
False

>>> 0 == True
False
>>> "" == True
False
>>> [] == True
False
>>> {} == True
False
>>> None == True
False

产生测试结果不一致的主要原因是Python在进行逻辑判断时,Python当中等于False的值并不只有False一个,它也有一套规则。官方说明为:

In the context of Boolean operations, and also when expressions are used by control 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). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method.

大致逻辑为:

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

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

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

正是基于以上规则,PEP 8 文档中才有类似的建议:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):

参考链接:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注