Python断言assert的用法代码解析
作者:祥知道 时间:2021-10-05 21:57:07
在开发一个程序时候,与其让它运行时崩溃,不如在它出现错误条件时就崩溃(返回错误)。这时候断言assert 就显得非常有用。
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)== int
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
assert type(a_str)== int
AssertionError
来源:http://blog.csdn.net/humanking7/article/details/45950781
标签:python,断言,assert
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
在import scipy.misc 后找不到 imsave的解决方案
2023-08-09 05:21:45
![](https://img.aspxhome.com/file/2023/1/62611_0s.jpg)
ASP 80040e14错误的解决方法
2011-03-17 11:21:00
CSS背景图片的运用优化HTTP连接数
2008-09-04 21:38:00
![](https://img.aspxhome.com/file/UploadPic/20089/4/200894214417934s.gif)
python 爬取小说并下载的示例
2023-08-24 19:31:49
![](https://img.aspxhome.com/file/2023/2/61962_0s.gif)
ASP向Excel导数据(图片)终结版 ASP操作Excel
2011-03-25 10:48:00
Python简单实现词云图代码及步骤解析
2021-05-13 00:25:52
![](https://img.aspxhome.com/file/2023/7/93517_0s.png)
XHTML与HTML之间的7个区别
2009-05-20 10:13:00
PHP中使用Memache作为进程锁的操作类分享
2023-11-22 18:10:02
innerHTML 的一些问题
2008-06-17 17:39:00
Python的互斥锁与信号量详解
2021-12-24 15:29:34
JS实现二维数组横纵列转置的方法
2023-08-29 21:54:05
![](https://img.aspxhome.com/file/2023/6/56206_0s.jpg)
Django框架静态文件处理、中间件、上传文件操作实例详解
2021-03-07 14:31:04
![](https://img.aspxhome.com/file/2023/0/68890_0s.png)
极简主义网站设计:寓丰富于简单
2009-12-07 21:37:00
![](https://img.aspxhome.com/file/UploadPic/200912/7/janreichle-67s.jpg)
两级联动select刷新后其值保持不变的实现方法
2023-11-05 11:39:33
Python绘画好看的星空图
2021-11-22 12:48:12
![](https://img.aspxhome.com/file/2023/7/86367_0s.gif)
支持在线写SQL的Oracle学习免费网站推荐!(个人常使用)
2023-07-24 09:06:51
![](https://img.aspxhome.com/file/2023/6/64476_0s.jpg)
Web UI 设计(网页设计)命名规范
2009-05-13 13:06:00
![](https://img.aspxhome.com/file/UploadPic/20095/13/web-ui-design-title1-57s.jpg)
对python requests发送json格式数据的实例详解
2023-12-11 05:16:07
FireScope-面向Web开发者和设计者的参考手册
2009-03-22 15:35:00
![](https://img.aspxhome.com/file/UploadPic/20093/22/01_b-44s.jpg)
PHP正则表达式替换<pre>标签外的内容
2023-05-22 10:47:12