在開發(fā)一個(gè)程序時(shí)候,與其讓它運(yùn)行時(shí)崩潰,不如在它出現(xiàn)錯(cuò)誤條件時(shí)就崩潰(返回錯(cuò)誤)。這時(shí)候斷言assert 就顯得非常有用。
python assert斷言是聲明布爾值必須為真的判定,如果發(fā)生異常就說明表達(dá)式為假。
可以理解assert斷言語句為raise-if-not,用來測(cè)試表示式,其返回值為假,就會(huì)觸發(fā)異常。
assert的語法格式:
assert expression
它的等價(jià)語句為:
if not expression: raise AssertionError
這段代碼用來檢測(cè)數(shù)據(jù)類型的斷言,因?yàn)?a_str 是 str 類型,所以認(rèn)為它是 int 類型肯定會(huì)引發(fā)錯(cuò)誤。
>>> a_str = 'this is a string'>>> type(a_str)<type 'str'>>>> assert type(a_str)== str>>> assert type(a_str)== intTraceback (most recent call last): File "<pyshell#41>", line 1, in <module> assert type(a_str)== intAssertionError
以上就是本文關(guān)于Python斷言assert的用法代碼解析的全部內(nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選