我们知道,Python中可以使用help('模块名')或者help(类名)的形式来查看一个模块或者类的帮助文档,我们也可以为自定义的类添加帮助文档,并用help进行查看.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 我们用三对双引号对类和其成员函数add进行了注释,那么我们就可以通过下面的方式查看该模块和类的帮助.查看模块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)我们在上面的模块中加入下面这段代码:
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.