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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短