[Python]断言assert的用法

来源:互联网 发布:杭州网络 编辑:程序博客网 时间:2024/06/05 12:47

原创文章,欢迎转载。转载请注明:转载自 祥的博客

原文链接:http://blog.csdn.net/humanking7/article/details/45950781


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

assert的语法格式:

assert expression

它的等价语句为:

if not expression:    raise AssertionError

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

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