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


当前回答

如果你想知道python中保留函数的确切功能,输入help(enter_keyword)

如果您正在输入保留关键字,请确保将其输入为字符串。

其他回答

正如其他答案所指出的,assert类似于在给定条件不为真时抛出异常。一个重要的区别是,如果使用优化选项-O编译代码,断言语句将被忽略。文档说断言表达式可以更好地描述为等效于

if __debug__:
   if not expression: raise AssertionError

如果你想彻底测试你的代码,然后在你高兴地看到你的断言案例都没有失败时发布一个优化版本,这可能是有用的——当优化打开时,__debug__变量变成False,条件将停止计算。如果您依赖断言,而没有意识到断言已经消失,该特性还可以发现这一点。

其他人已经为您提供了文档链接。

您可以在交互式shell中尝试以下操作:

>>> assert 5 > 2
>>> assert 2 > 5
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.AssertionError:

第一个语句什么都不做,而第二个语句引发异常。这是第一个提示:断言用于检查在代码的给定位置(通常是函数的开始(前置条件)和结束(后置条件)中应该为真条件。

断言实际上与契约编程高度相关,这是一种非常有用的工程实践:

http://en.wikipedia.org/wiki/Design_by_contract。

def getUser(self, id, Email):

    user_key = id and id or Email

    assert user_key

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

这是一个简单的例子,保存到文件(比如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后的语句为真,则程序继续执行,但如果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