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


当前回答

正如C2 Wiki上简要总结的那样:

断言是程序中特定位置的布尔表达式,除非程序中存在错误,否则该表达式将为真。

您可以使用断言语句来记录您对特定程序点上代码的理解。例如,您可以记录关于输入(前提条件)、程序状态(不变量)或输出(后置条件)的假设或保证。

如果断言失败,这是对您(或您的后继者)的一个警告,说明您在编写程序时对程序的理解是错误的,并且可能包含一个错误。

有关更多信息,John Regehr有一篇关于断言的使用的精彩博客文章,它也适用于Python断言语句。

其他回答

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将引发断言错误,这有助于开发人员识别发生了不可能的事情。

希望能有所帮助。

>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)

>>> #first we try without assert
>>>if test_us == True:
    print("YES! I am right!")
else:
    print("I am Wrong, but the program still RUNS!")

I am Wrong, but the program still RUNS!


>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    assert test_us
AssertionError
>>> 

如果assert关键字后面的代码为False, Python中的assert关键字将引发AssertionError。如果没有,它继续什么都没有发生。

示例1:

a = 5
b = 6

assert a == b

输出:

AssertionError

这是因为,很明显,a不等于b。 如果你想在代码中引发一个异常,这是特别有用的。

def get_dict_key(d, k):
    try:
        assert k in d
        return d[k]
    except Exception:
        print("Key must be in dict.")

上面的示例实际上是无用的,但是请记住,它主要用于调试目的,因此您可以跟踪错误。

如果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

我的简单解释是:

如果表达式为假,assert会引发AssertionError,否则只是继续代码,如果有逗号,无论它是什么,它都会在逗号后引发AssertionError: whatever,而to code则是:引发AssertionError(逗号后的whatever)

相关教程:

https://www.tutorialspoint.com/python/assertions_in_python.htm