zoukankan      html  css  js  c++  java
  • python断言语句assert

    断言语句的格式

    assert test, [msg]
    

    test是一个表达式,表达式求值为Fals时引发AssertionError异常,msg是可选的异常消息。

    def test_assert(a):
        """
        当输入的参数不大于0时断言抛出异常
        """
        assert a > 0, 'a需要大于0'
        print('a=', a)
    
    
    test_assert(-10)
    

    运行test_assert(-10)程序将抛出异常:
    Traceback (most recent call last):
    File "M:/project/untitled1/testdatetime.py", line 788, in
    main()
    File "M:/project/untitled1/testdatetime.py", line 303, in main
    test_assert(-10)
    File "M:/project/untitled1/testdatetime.py", line 293, in test_assert
    assert a > 0, 'a需要大于0'
    AssertionError: a需要大于0

    断言使用注意

    • 断言只能作为辅助调试手段使用,在表达式为False时抛出异常终止程序执行,不能在程序中代替条件判断语句,因为程序以优化方式运行时不会执行断言语句。
    • 添加-O参数程序运行在优化模式,不会输出断言
      python -O main.py
  • 相关阅读:
    etcd的原理分析
    (转)Linux sort命令
    随机森林
    python 类的定义和继承
    python random
    Spark源码阅读(1): Stage划分
    Mac 上安装MySQL
    Python 删除 数组
    在循环中将多列数组组合成大数组
    准确率 召回率
  • 原文地址:https://www.cnblogs.com/bryant24/p/11433946.html
Copyright © 2011-2022 走看看