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
新聞熱點
疑難解答