zoukankan      html  css  js  c++  java
  • Python全栈开发之---assert断言

    一、python assert的作用:

    根据Python 官方文档解释(https://docs.python.org/3/reference/simple_stmts.html#assert), "Assert statements are a convenient way to insert debugging assertions into a program".

    二、一般的用法是:

    1 assert condition
    2 用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于:
    3 
    4 if not condition:
    5     raise AssertionError()

    例如:

     1 >>> assert 1==1
     2 >>> assert 1==0
     3 Traceback (most recent call last):
     4   File "<pyshell#1>", line 1, in <module>
     5     assert 1==0
     6 AssertionError
     7 >>> assert True
     8 >>> assert False
     9 Traceback (most recent call last):
    10   File "<pyshell#3>", line 1, in <module>
    11     assert False
    12 AssertionError
    13 >>> assert 3<2
    14 Traceback (most recent call last):
    15   File "<pyshell#4>", line 1, in <module>
    16     assert 3<2
    17 AssertionError

    三、如何为assert断言语句添加异常参数

      assert的异常参数,其实就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。格式如下:

    assert expression [, arguments]
    assert 表达式 [, 参数]

    例如:

     1 >>> assert len(lists) >=5,'列表元素个数小于5'
     2 Traceback (most recent call last):
     3 File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
     4 assert 2>=5,'列表元素个数小于5'
     5 AssertionError: 列表元素个数小于5
     6 >>> assert 2==1,'2不等于1'
     7 Traceback (most recent call last):
     8 File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
     9 assert 2==1,'2不等于1'
    10 AssertionError: 2不等于1
  • 相关阅读:
    Flex 和JavaScript 交互(带参)
    dos创建快捷方式
    IE的onunload事件里调用DWR
    使用VS2008开发OPC客户端程序
    实时库GEHistorian的一些问题记录
    SQL SERVER中,把一个表中的数据导入到另一个表中
    SQLSERVER 触发器
    SqlServer数据复制出现的问题与处理
    了解Log.Debug 或 log4net
    VS2008应用程序部署时将Framework3.5打包到安装包中
  • 原文地址:https://www.cnblogs.com/xuechaojun/p/10200770.html
Copyright © 2011-2022 走看看