python中assert详解

assert基础

  • 官方解释:"Assert statements are a convenient way to insert debugging assertions into a program"。

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

一般用法如下:

assert condition,'自定义错误显示信息'

用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同如下:

if not condition:
    raise AssertionError()

什么时候用assert

那什么时候应该使用assert?没有特定的规则,断言应该用于:

  • 防御型的编程

  • 运行时检查程序逻辑

  • 检查约定

  • 程序常量

  • 检查文档

猜你喜欢

转载自www.cnblogs.com/wujingqiao/p/9668743.html