在Python中使用“assert”有什么用?
发布时间:2025-05-24 16:40:26
作者:益华网络
来源:undefined
浏览量(2)
点赞(1)
摘要:我一直在阅读一些源代码,在一些地方我已经看到了 assert的用法。 这究竟是什么意思? 它的用途是什么? #1楼 断言语句有两种形式。 简单的形式, assert
我一直在阅读一些源代码,在一些地方我已经看到了 assert的用法。
这究竟是什么意思? 它的用途是什么?
#1楼
断言语句有两种形式。
简单的形式, assert <expression> ,相当于
1
2
if __debug__:
if not <expression>: raise AssertionError
扩展形式 assert <expression1>, <expression2>等同于
1
2
if __debug__:
if not <expression1>: raise AssertionError, <expression2>
#2楼
这是一个简单的例子,将其保存在文件中(假设为b.py)
1
2
3
def chkassert(num):
assert type(num) == int
chkassert(a)
和 $python b.py时的结果
1
2
3
Traceback (most recent call last): File "b.py", line 5, in <module>
chkassert(a) File "b.py", line 2, in chkassert
assert type(num) == intAssertionError
#3楼
断言是一种系统的方法,用于检查程序的内部状态是否与程序员预期的一样,目的是捕获错误。 请参阅下面的示例。
1
2
3
>>> number = input(Enter a positive number:)
Enter a positive number:-1>>> assert (number > 0), Only positive numbers are allowed!Traceback (most recent call last):
File "<stdin>", line 1, in <module>AssertionError: Only positive numbers are allowed!>>>
#4楼
如果assert之后的语句为true,则程序继续,但如果assert之后的语句为false,则程序会给出错误。 就那么简单。
例如:
1
2
3
4
assert 1>0 #normal executionassert 0>1 #Traceback (most recent call last):
#File "<pyshell#11>", line 1, in <module>
#assert 0>1
#AssertionError
#5楼
format:assert Expression [,arguments]当assert遇到一个语句时,Python会计算表达式。如果该语句不为true,则引发异常(assertionError)。 如果断言失败,Python使用ArgumentExpression作为AssertionError的参数。 可以使用try-except语句像任何其他异常一样捕获和处理AssertionError异常,但如果不处理,它们将终止程序并产生回溯。 例:
1
2
3
4
5
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
执行上面的代码时,会产生以下结果:
1
2
3
4
5
6
7
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!" AssertionError: Colder than absolute zero!
扫一扫,关注我们
声明:本文由【益华网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【益华网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。
1