python断言小窍门(python selenium断言)

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

python断言小窍门

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)== intTraceback (most recent call last):File "<pyshell#41>", line 1, in <module>assert type(a_str)== intAssertionError

总结

以上就是本文关于Python断言assert的用法代码解析的全部内容,希望对大家有所帮助。

【声明】任何单位或个人未经本站书面授权不得转载、链接、转贴或以其他方式复制发表。否则,本站将依法追究其法律责任。

本文链接:https://www.xiaozhujop.com/a/363b687fde5c60.html