断言是什么意思?它是如何使用的?
当前回答
其他人已经为您提供了文档链接。
您可以在交互式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。
其他回答
我的简单解释是:
如果表达式为假,assert会引发AssertionError,否则只是继续代码,如果有逗号,无论它是什么,它都会在逗号后引发AssertionError: whatever,而to code则是:引发AssertionError(逗号后的whatever)
相关教程:
https://www.tutorialspoint.com/python/assertions_in_python.htm
def getUser(self, id, Email):
user_key = id and id or Email
assert user_key
可用于确保在函数调用中传递参数。
如果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
>>>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
>>>
如果你想知道python中保留函数的确切功能,输入help(enter_keyword)
如果您正在输入保留关键字,请确保将其输入为字符串。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录