Python中如何以注释方式为类添加帮助文档并利用doctest进行文档测试
1。通过评论向班级添加帮助文档

我们知道,在Python中,我们可以使用帮助(“模块名称”)或帮助(类名)查看模块或类的帮助文档。我们还可以将帮助文档添加到自定义课程中,并使用帮助查看它们。 Python您可以使用三对双引号来进行多行注释。当我们将此注释内容放在类或功能定义下方时,它将自动视为类或功能的帮助文档。请参阅以下课程:
Docts.py:
#coding:utf-8
class MyMath:
"""
A class with math operator
"""
def add(self,x,y):
"""
Function to get the sum of x and y.
Example:
>>> mt=MyMath()
>>> mt.add(1,2)
3
>>> mt.add(3,-2)
1
>>> mt.add(2.4,1.5)
3.9
"""
return x+y
我们评论了类及其成员功能,添加了三对双引号,因此我们可以通过以下方式查看模块和类的帮助。
查看模块Docts.py:
>>> help('docts')
Help on module docts:
NAME
docts - #coding:utf-8
FILE
/home/hyman/projects/pythonTs/docts.py
CLASSES
MyMath
class MyMath
| A class with math operator
|
| Methods defined here:
|
| add(self, x, y)
| Function to get the sum of x and y.
| Example:
| >>> mt=MyMath()
| >>> mt.add(1,2)
| 3
| >>> mt.add(3,-2)
查看班级mymath:
>>> from docts import MyMath
>>> help(MyMath)
Help on class MyMath in module docts:
class MyMath
| A class with math operator
|
| Methods defined here:
|
| add(self, x, y)
| Function to get the sum of x and y.
| Example:
| >>> mt=MyMath()
| >>> mt.add(1,2)
| 3
| >>> mt.add(3,-2)
| 1
| >>> mt.add(2.4,1.5)
| 3.9
(END)
2。使用医生进行文档测试
我们将以下代码添加到上述模块:
if __name__=='__main__':
import doctest
doctest.testmod()
请在我们写的评论中注意以下段落:
Example:
>>> mt=MyMath()
>>> mt.add(1,2)
3
>>> mt.add(2.4,1.5)
3.9
当我们在终端中运行模块时,导入doctest.testmod()将自动测试我们在终端中写的示例:
hyman@hyman-VirtualBox:~/projects/pythonTs$ python docts.py
hyman@hyman-VirtualBox:~/projects/pythonTs$
运行后,您会发现没有打印结果。那是因为我们写的示例是正确的。我们可以在以下示例中修改代码,并在错误中纠正操作结果。
>>> mt.add(3,-2)
0
如果再次运行,您将报告一个错误(请注意,在编写运行示例时,>>>和Python语句之间必须有一个空间,否则将发生语法错误。
hyman@hyman-VirtualBox:~/projects/pythonTs$ python docts.py ********************************************************************** File "docts.py", line 13, in __main__.MyMath.add Failed example: mt.add(3,-2) Expected: 0 Got: 1 ********************************************************************** 1 items had failures: 1 of 4 in __main__.MyMath.add ***Test Failed*** 1 failures.