断言是什么意思?它是如何使用的?


当前回答

从文档:

断言语句是向程序中插入调试断言的一种方便方法

你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html

其他回答

Python assert基本上是一种调试辅助工具,用于测试代码内部自检的条件。 当代码进入不可能的边缘情况时,Assert使调试变得非常容易。断言检查那些不可能的情况。

假设有一个函数计算商品折扣后的价格:

def calculate_discount(price, discount):
    discounted_price = price - [discount*price]
    assert 0 <= discounted_price <= price
    return discounted_price

这里,discounted_price永远不能小于0并且大于实际价格。因此,如果上述条件被违反,assert将引发断言错误,这有助于开发人员识别发生了不可能的事情。

希望能有所帮助。

这是一个简单的例子,保存到文件(比如b.py)

def chkassert(num):
    assert type(num) == int


chkassert('a')

当$python b.py

Traceback (most recent call last):
  File "b.py", line 5, in <module>
    chkassert('a')
  File "b.py", line 2, in chkassert
    assert type(num) == int
AssertionError

assert语句几乎存在于每一种编程语言中。它有两个主要用途:

它有助于在程序的早期(原因很清楚的时候)检测问题,而不是在其他一些操作失败的时候。例如,Python中的类型错误如果没有在早期被捕获,可能会在实际引发异常之前经历几层代码。 对于阅读代码的其他开发人员来说,它可以作为文档使用,他们看到断言后可以自信地说从现在开始它的条件是成立的。

当你……

assert condition

... 您告诉程序测试该条件,如果条件为假,则立即触发一个错误。

在Python中,它大致相当于:

if not condition:
    raise AssertionError()

在Python shell中试试:

>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

断言可以包含可选的消息,您可以在运行解释器时禁用它们。

如果断言失败,打印一条消息:

assert False, "Oh no! This assertion failed!"

不要像调用函数一样使用括号来调用assert。这是一个声明。如果执行断言(condition, message),则运行断言时将使用(condition, message)元组作为第一个参数。

至于禁用它们,当以优化模式运行python时,其中__debug__为False, assert语句将被忽略。只需要传递-O标志:

python -O script.py

相关文档请参见这里。

如果assert后的语句为真,则程序继续执行,但如果assert后的语句为假,则程序报错。就这么简单。

例如:

assert 1>0   #normal execution
assert 0>1   #Traceback (most recent call last):
             #File "<pyshell#11>", line 1, in <module>
             #assert 0>1
             #AssertionError

从文档:

断言语句是向程序中插入调试断言的一种方便方法

你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html