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

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

那帮助文档通常会写什么内容呢?主要包括如下内容:app

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

  • 传入的值和输出的值测试

  • 一些特殊状况的说明ui

  • 文档测试内容code

以上内容是我的的总结,可是并无看到相关的资料。ip

咱们来举一个例子:文档

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输入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模块进行文档测试。get

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

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()

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

相关文章
相关标签/搜索