Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Truth Value Testing ใน Python


ออบเจ็กต์ใดๆ ก็สามารถทดสอบค่าความจริงได้ ผ่านคำสั่ง if หรือ while

ค่าความจริงเป็น True จนกว่า __bool__() จะคืน False หรือ __len__() คืน 0

ค่าที่ถือว่า False

  • ค่าคงที่: False, None
  • ตัวเลขศูนย์: 0, 0.0, Fraction(0,1), Decimal(0), 0j
  • Sequence/Collection ว่าง: '', [], (), {}, set(), range(0)

0 เทียบเท่า False, 1 เทียบเท่า True

ตัวอย่างโค้ด

class A:
    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:
    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 = []
if myList:
    print('It has some elements')
else:
    print('It has no elements')

mySet = (10, 47, 84, 15)
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