详解python3中的真值测试

yipeiwu_com6年前Python基础

1. 真值测试

所谓真值测试,是指当一种类型对象出现在if或者while条件语句中时,对象值表现为True或者False。弄清楚各种情况下的真值对我们编写程序有重要的意义。

对于一个对象a,其真值定义为:

  • True : 如果函数truth_test(a)返回True。
  • False:如果函数truth_test(a)返回False。

以if为例(while是等价的,不做赘述),定义函数truth_test(x)为:

def truth_test(x):
  if x:
    return True
  else:
    return False

2.对象的真值测试

一般而言,对于一个对象,在满足以下条件之一时,真值测试为False;否则真值测试为True。

  • 其内置函数__bool__()返回False
  • 其内置函数__len__()返回0

(1)以下类型对象真值测试为真:

class X:
   pass

(2)以下真值测试为假:

class Y:
   def __bool__(self):
     return False

(3)以下真值测试为假:

class Z:
   def __len__(self):
     return 0

进入python3脚本环境,测试过程如下:

>>> class X:
...   pass
... 
>>> class Y:
...   def __bool__(self):
...     return False
... 
>>> class Z:
...   def __len__(self):
...     return 0
... 
>>> def truth_test(x):
...   if x:
...     return True
...   else:
...     return False
... 
>>> x = X()
>>> y = Y()
>>> z = Z()
>>> truth_test(x)
True
>>> truth_test(y)
False
>>> truth_test(z)
False
>>>

3. 常见对象的真值

下面是常见的真值为False的情况:

  • 常量:None and False.
  • 数值0值: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • 序列或者集合为空:'', (), [], {}, set(), range(0)

进入python3脚本环境,测试过程如下:

>>> truth_test(None)
False
>>> truth_test(False)
False
>>> truth_test(0)
False
>>> truth_test(0.0)
False
>>> truth_test(0j)  #复数
False
>>> truth_test(Decimal(0)) #十进制浮点数
False
>>> truth_test(Fraction(0,1)) #分数
False
>>> truth_test(Fraction(0,2)) #分数
False
>>> truth_test('')
False
>>> truth_test(())
False
>>> truth_test({})
False
>>> truth_test(set())
False
>>> truth_test(range(0)) #序列
False
>>> truth_test(range(2,2)) #序列
False

此外的其它取值,真值测试应当为True。

4.一些有意思的例子

下面是一些有意思的例子,原理不超出前面的解释。

>>> if 1 and Fraction(0,1):
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and ():
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and range(0):
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1 and None:
...   print(True)
... else:
...   print(False)
... 
False
>>> if 1+2j and None:
...   print(True)
... else:
...   print(False)
... 
False

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python网络编程之文件下载实例分析

本文实例讲述了python网络编程之文件下载实现方法。分享给大家供大家参考。具体如下: 真是越看越喜欢python啊,想要了解它提供的http和ftp下载功能,原来是如此的简单。 1、相...

详解Python可视化神器Yellowbrick使用

详解Python可视化神器Yellowbrick使用

机器学习中非常重要的一环就是数据的可视化分析,从源数据的可视化到结果数据的可视化都离不开可视化工具的使用,sklearn+matplotlib的组合在日常的工作中已经满足了绝对大多数的需...

python遍历文件夹,指定遍历深度与忽略目录的方法

背景 需要在文件夹中搜索某一文件,找到后返回此文件所在目录。用最常规的os.listdir()方式实现了一版,但执行时报错:递归超过最大深度。于是自己添加了点功能,之所有写此函数是为了让...

python logging模块的使用总结

日志级别 CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 logging.basicConfig()函数中的具...

Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析

Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析

本文实例讲述了Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法。分享给大家供大家参考,具体如下: 函数的返回值: 函数一旦执行到&...