เราสามารถใช้วัตถุใดก็ได้เพื่อทดสอบค่าความจริง โดยให้เงื่อนไขใน if หรือ ในขณะที่ คำสั่งตรวจสอบได้
จนกว่าคลาส method __bool__() จะคืนค่า False หรือ __len__() คืนค่า 0 เราสามารถพิจารณาค่าความจริงของวัตถุนั้น True .
-
ค่าของค่าคงที่คือ False เมื่อเป็นเท็จหรือ ไม่มี .
-
เมื่อตัวแปรมีค่าต่างๆ เช่น 0, 0.0, Fraction(0, 1), Decimal(0), 0j จะหมายถึงค่าเท็จ
-
ลำดับว่าง ‘‘, [], (), {}, set(0), range(0), Truth value of these elements are False .
ค่าความจริง 0 เท่ากับ เท็จ และ 1 เหมือนกับ จริง .
โค้ดตัวอย่าง
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