1. 程式人生 > 程式設計 >Python3 assert斷言實現原理解析

Python3 assert斷言實現原理解析

語法格式如下:

assert expression

等價於:

if not expression:
 raise AssertionError

assert 後面也可以緊跟引數:

assert expression [,arguments]

等價於:

if not expression:
 raise AssertionError(arguments)

以下為 assert 使用例項:

>>> assert True   # 條件為 true 正常執行
>>> assert False  # 條件為 false 觸發異常
Traceback (most recent call last):
 File "<stdin>",line 1,in <module>
AssertionError
>>> assert 1==1  # 條件為 true 正常執行
>>> assert 1==2  # 條件為 false 觸發異常
Traceback (most recent call last):
 File "<stdin>",in <module>
AssertionError 
>>> assert 1==2,'1 不等於 2'
Traceback (most recent call last):
 File "<stdin>",in <module>
AssertionError: 1 不等於 2

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。