Python真值测试
我们可以使用任何对象来测试真实值。通过在if或while语句中提供条件,可以完成检查。
在类方法__bool__()返回False或__len__()方法返回0之前,我们可以认为该对象的真值是True。
常量的值为False,如果为False,则为None。
当变量包含不同的值(例如0、0.0,小数(0、1),小数,0j)时,则表示False值。
这些元素的空序列'',[],(),{},set,range,Truth值为True。
真值0等于False,而1等于True。
范例程式码
class A: #The class A has no __bool__ method, so default value of it is True def __init__(self): print('This is class A') a_obj = A()if a_obj: print('It is True') else: print('It is False') class B: #The class B has __bool__ method, which is returning false value def __init__(self): print('This is class B') def __bool__(self): return False b_obj = B()if b_obj: print('It is True') else: print('It is False') myList = [] # No element is available, so it returns False if myList: print('It has some elements') else: print('It has no elements') mySet = (10, 47, 84, 15) # Some elements are available, so it returns True if mySet: print('It has some elements') else: print('It has no elements')
输出结果
This is class A It is True This is class B It is False It has no elements It has some elements