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


当前回答

def getUser(self, id, Email):

    user_key = id and id or Email

    assert user_key

可用于确保在函数调用中传递参数。

其他回答

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

希望能有所帮助。

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

相关文档请参见这里。

断言是一种系统的方法,用于检查程序的内部状态是否如程序员所期望的那样,目的是捕捉错误。请参阅下面的示例。

>>> 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!
>>> 

我的简单解释是:

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

相关教程:

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

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