• 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
  • 相关阅读:
    C# 程序一个cmd命令窗口执行多条dos命令
    单例模式学习
    C#中的typeof()和GetType()的区别
    C#判断字符串A是否包含字符串B--by winter
    ASP.NET内置对象Session缺点及解决办法---by winter
    冒泡排序--by winter
    as关键字---?号用法---各种路径
    自创page类中获取当前用户权限 --by winter
    自建的Page类的使用--by winter
    无法添加App_Code文件的解决办法
  • 原文地址:https://www.cnblogs.com/xuechaojun/p/10200770.html
Copyright © 2020-2023  润新知