如何使用docstrings
编写一个简单的程序来计算阶乘,但该程序没有覆盖所有可能的边界条件。也就是说,某些测试项目是通不过的。
- 编写docstring
"""
Test for the factorial of 3 that should pass.
>>> factorial(3)
6
Test for the factorial of 0 that should fail.
>>> factorial(0)
1
"""
- 编写NumPy代码
def factorial(n):
return numpy.arange(1, n+1).cumprod()[-1]
执行测试
完整代码
import numpy import doctest def factorial(n): """ Test for the factorial of 3 that should pass. >>> factorial(3) 6 Test for the factorial of 0 that should fail. >>> factorial(0) 1 """ return numpy.arange(1, n+1).cumprod()[-1] doctest.testmod()
- 详细输出
- 简略输出
由于出现数组为空的情况,得到了一个索引超出边界(index out of bounds)的错误
什么是docstrings
docstring是嵌入在Python代码中的字符串, 其内容看上去有点像交互式的会话。
这些字符串可用来检查某些假设, 或仅仅把他们看作是一些范例代码。
我们需要doctest模块运行这些测试。