欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python斷言assert的用法代碼解析

 更新時間:2018年02月03日 15:03:54   作者:祥知道  
這篇文章主要介紹了Python斷言assert的用法代碼解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下

在開發(fā)一個程序時候,與其讓它運行時崩潰,不如在它出現(xiàn)錯誤條件時就崩潰(返回錯誤)。這時候斷言assert 就顯得非常有用。

python assert斷言是聲明布爾值必須為真的判定,如果發(fā)生異常就說明表達式為假。

可以理解assert斷言語句為raise-if-not,用來測試表示式,其返回值為假,就會觸發(fā)異常。

assert的語法格式:

assert expression

它的等價語句為:

if not expression:
  raise AssertionError

這段代碼用來檢測數(shù)據(jù)類型的斷言,因為 a_str 是 str 類型,所以認為它是 int 類型肯定會引發(fā)錯誤。

>>> a_str = 'this is a string'
>>> type(a_str)
<type 'str'>
>>> assert type(a_str)== str
>>> assert type(a_str)== int

Traceback (most recent call last):
 File "<pyshell#41>", line 1, in <module>
  assert type(a_str)== int
AssertionError

總結(jié)

以上就是本文關(guān)于Python斷言assert的用法代碼解析的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

相關(guān)文章

最新評論