斷言聲明是一種方便的程序調(diào)試方式。
1、可將斷言視為debug工具,Python的實(shí)現(xiàn)也符合這種設(shè)計(jì)理念。assert語句的執(zhí)行依賴于__debug__,且默認(rèn)值為True。
2、如果__debug__為True,則僅執(zhí)行assert語句。
實(shí)例
assert 可以同時(shí)聲明兩個(gè) expression,例如 assert expression1, expression2 等價(jià)于
1
2
|
if __debug__: if not expression1: raise AssertionError(expression2) |
如果執(zhí)行腳本文件時(shí)加上-O參數(shù), __debug__則為False。
知識(shí)點(diǎn)擴(kuò)展:
簡單用法是:
assert expression
讓我們用程序來測試這個(gè)expression,如果expression相當(dāng)于False,那么raise一個(gè)AssertionError出來。
即邏輯上等同于:
1
2
|
if not expression: raise AssertionError |
簡單看看這些例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
>>> assert True >>> assert False Traceback (most recent call last): File "<pyshell#3>" , line 1 , in <module> assert False AssertionError >>> assert 1 = = 1 >>> assert 1 = = 0 Traceback (most recent call last): File "<pyshell#1>" , line 1 , in <module> assert 1 = = 0 AssertionError >>> assert [ 1 , 2 ] # 非空列表值得注意一下,雖說也沒個(gè)啥,哈哈 >>> assert not [ 1 , 2 ] Traceback (most recent call last): File "<ipython-input-48-eae410664122>" , line 1 , in <module> assert not [ 1 , 2 ] AssertionError |
到此這篇關(guān)于python assert斷言的實(shí)例用法的文章就介紹到這了,更多相關(guān)python assert斷言的使用內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.py.cn/jishu/jichu/33869.html