网络编程
位置:首页>> 网络编程>> Python编程>> Python断言assert的用法代码解析

Python断言assert的用法代码解析

作者:祥知道  发布时间:2021-10-05 21:57:07 

标签:python,断言,assert

在开发一个程序时候,与其让它运行时崩溃,不如在它出现错误条件时就崩溃(返回错误)。这时候断言assert 就显得非常有用。

python assert断言是声明布尔值必须为真的判定,如果发生异常就说明表达式为假。

可以理解assert断言语句为raise-if-not,用来测试表示式,其返回值为假,就会触发异常。

assert的语法格式:


assert expression

它的等价语句为:


if not expression:
 raise AssertionError

这段代码用来检测数据类型的断言,因为 a_str 是 str 类型,所以认为它是 int 类型肯定会引发错误。


>>> 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

来源:http://blog.csdn.net/humanking7/article/details/45950781

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com