python assert的作用


一、python assert的作用:

根據Python 官方文檔解釋(https://docs.python.org/3/reference/simple_stmts.html#assert), "Assert statements are a convenient way to insert debugging assertions into a program".

 

二、一般的用法是:

assert condition

用來讓程序測試這個condition,如果condition為false,那么raise一個AssertionError出來。邏輯上等同於:

if not condition:
    raise AssertionError()

比如如下的例子:

>>> assert 1==1
>>> assert 1==0
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    assert 1==0
AssertionError
>>> assert True
>>> assert False
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert False
AssertionError
>>> assert 3<2
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    assert 3<2
AssertionError

三、如何為assert斷言語句添加異常參數

  assert的異常參數,其實就是在斷言表達式后添加字符串信息,用來解釋斷言並更好的知道是哪里出了問題。格式如下:

assert expression [, arguments]
assert 表達式 [, 參數]

 

比如如下的例子:

>>> assert len(lists) >=5,'列表元素個數小於5'

Traceback (most recent call last):
File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
assert 2>=5,'列表元素個數小於5'
AssertionError: 列表元素個數小於5

>>> assert 2==1,'2不等於1'

Traceback (most recent call last):
File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
assert 2==1,'2不等於1'
AssertionError: 2不等於1

--------------------------------------------------------------------

參考鏈接:

https://www.cnblogs.com/liuchunxiao83/p/5298016.html

https://www.cnblogs.com/cedrelaliu/p/5948567.html

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM