python学习笔记-为自定义类或者函数编写help文档,以及进行文档测试

在python中我们可以利用help("模块名")或者help(类名)的方式来查看类或者函数的文档。但是它们是如何编写的呢?
其实它们在类最前面或者方法的最前面用"""三个双引号包裹了多行注释。这些内容就会被Python当成帮助文档。

那帮助文档一般会写什么内容呢?主要包括以下内容:

  • 该类或者函数的主要作用

  • 传入的值和输出的值

  • 一些特殊情况的说明

  • 文档测试内容

以上内容是个人的总结,但是并没有看到相关的资料。

我们来举一个例子:

class Apple(object):
    """ This is an Apple Class"""

    def get_color(self):
        """
        Get the Color of Apple.
        get_color(self) -> str
        """
        return "red"

在python terminal输入

>>> from CallDemo import Apple
>>> help(Apple)
Help on class Apple in module CallDemo:

class Apple(__builtin__.object)
 |  This is an Apple Class
 |  
 |  Methods defined here:
 |  
 |  get_color(self)
 |      Get the Color of Apple.
 |      get_color(self) -> str
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
利用doctest进行文档测试

我们在注释中我们也可以doctest模块进行文档测试。

例如,我们添加了文档测试内容后如下所示:

class Apple(object):
    """
    This is an Apple Class

    Example:
        >>> apple = Apple()
        >>> apple.get_color()
        'red'
        >>> apple.set_count(20)
        >>> apple.get_count()
        400

    """

    def get_color(self):
        """
        Get the Color of Apple.
        get_color(self) -> str
        """
        return "red"

    def set_count(self, count):
        self._count = count

    def get_count(self):
        return self._count * self._count


if __name__ == '__main__':
    import doctest

    doctest.testmod()

由于我们写了


if __name__ == '__main__':
    import doctest

    doctest.testmod()

所以以上文档测试只有在以入口文件执行的时候才会进行文档测试。因此并不会在实际应用在执行文档测试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值