python的help文档看不懂_Python自编写help文档以及文档测试

本文介绍了如何在Python中为类添加帮助文档,使用三对双引号创建多行注释作为类和方法的说明。同时,通过doctest模块展示了如何进行文档测试,确保代码示例的正确性。在终端运行模块时,doctest会自动验证注释中的代码例子,如果例子错误,会输出测试失败的信息。
摘要由CSDN通过智能技术生成

一 以注释方式为类添加帮助文档

我们知道,Python中可以使用help('模块名')或者help(类名)的形式来查看一个模块或者类的帮助文档,我们也可以为自定义的类添加帮助文档,并用help进行查看.Python中用三对双引号可以进行多行注释,当我们把这种注释内容放到一个类或者函数定义的下面时,它会自动被当作该类或者函数的帮助文档.请看下面的类:

[python] view plain copy

#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进行了注释,那么我们就可以通过下面的方式查看该模块和类的帮助.

[plain] view plain copy

>>> help('docts')

[plain] view plain copy

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:

[plain] view plain copy

>>> from docts import MyMath

>>> help(MyMath)

[plain] view plain copy

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)

二 利用doctest进行文档测试

我们在上面的模块中加入下面这段代码:

[python] view plain copy

if __name__=='__main__':

import doctest

doctest.testmod()

请注意我们写的注释中的下面这段内容:

[plain] view plain copy

Example:

>>> mt=MyMath()

>>> mt.add(1,2)

3

>>> mt.add(2.4,1.5)

3.9

当我们在终端中运行该模块时,导入doctest.testmod()会自动在终端测试我们所写的这些例子:

[plain] view plain copy

hyman@hyman-VirtualBox:~/projects/pythonTs$ python docts.py

hyman@hyman-VirtualBox:~/projects/pythonTs$

运行之后你会发现,什么结果都没打印,那是因为我们写的例子是正确的,我们可以修改下例子中代码,把运算结果改错

[plain] view plain copy

>>> mt.add(3,-2)

0

再运行就报错了(注意写运行示例时,>>>和python语句之间要有一个空格,否则会出现语法错误.)

[plain] view plain copy

[plain] view plain copy

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.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值