python3中的真值測試

來源:互聯網
上載者:User

標籤:action   函數   環境   編寫   解釋   過程   self   lse   cti   

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

python3中的真值測試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.